spring IoC (IDEA)—— 基于注解的AOP

Spring除了支持Schema(XML)方式配置AOP,还支持注解方式,使用@AspectJ风格的切面声明。Spring默认不支持@AspectJ风格的切面声明,需要进行配置。

1.开启AOP注解配置

    

2.在切面类上和方法上增加注解

package com.etc.service.impl;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

//定义切面类
@Component
@Aspect
public class LogAspects {
    //前置通知
    @Before("execution(* com.etc.service..*.*(..))")
    public void beforeAdvice(JoinPoint jp) throws Exception{
        MethodSignature signature = (MethodSignature) jp.getSignature();
        Method method = signature.getMethod();
        System.out.println( method.getName() + "方法执行开始....");
    }

    //后置通知
    @After("execution(* com.etc.service..*.*(..))")
    public void afterAdvice(JoinPoint jp){
        MethodSignature signature = (MethodSignature) jp.getSignature();
        Method method = signature.getMethod();
        System.out.println( method.getName() + "方法执行完成了....");
    }

    //环绕通知
    @Around("execution(* com.etc.service..*.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        System.out.println( method.getName() + "方法(环绕通知)执行开始....");
        Object result = pjp.proceed();
        System.out.println( method.getName() + "方法(环绕通知)执行结束....");
        return result;
    }
}

3.测试

package com.etc.test;

import com.etc.service.impl.UserServiceImpl2;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAop4Cglib {
    private ApplicationContext context;
    @Before
    public void init(){
        context = new ClassPathXmlApplicationContext("applicationContext.xml");
    }

    @Test
    public void testAdvice(){
        UserServiceImpl2 userServiceImpl2 = (UserServiceImpl2)context.getBean("userServiceImpl2");
        System.out.println("类名:" + userServiceImpl2.getClass().getName());
        userServiceImpl2.addUser();
        userServiceImpl2.editUser();
    }
}

 

你可能感兴趣的:(spring,IDEA)