11.Java代码配置AOP

68 阅读2分钟

6.3 注解模式

直接在Java在Java代码中去定义切面

/**
 * LogAdvice1 就是切面= 切点+通知
 */
//注册到容器中
@Component
//标记,指明当前类是一个切面
@Aspect
//开启自动代理

//proxyTargetClass 这个参数可以不加,Spring 会自动去选择 Java动态代理还是CGLIB,如果加了参数,设置为ture,则会使用CGLIB代理

@EnableAspectJAutoProxy(proxyTargetClass = truepublic class LogAdvice1 {

    //切点就是方法
    @Pointcut("execution(* org.luckboy.demo.ICalculatorImpl.*(..))")
    public void pc1(){

    }

    @Around("pc1()")
    public Object around(ProceedingJoinPoint pjp){
        Object proceed;
        try {
            //这句相当于是前置通知
            long startTime = System.currentTimeMillis();
            //这句话其实就是执行目标方法
            proceed = pjp.proceed();
            long endTime = System.currentTimeMillis();
        } catch (Throwable e) {
            //这里就是异常通知
            throw new RuntimeException(e);
        }
        return proceed;
    }


    /**
     * 前置通知
     */
    @Before("pc1()")
    public void before(JoinPoint jp){
        //获取目标方法的名字
        String name = jp.getSignature().getName();
        System.out.println(name+"方法开始执行了");
    }
    /**
     * 后置通知
     */
    @After("pc1()")
    public void after(JoinPoint jp){
        //获取目标方法的名字
        String name = jp.getSignature().getName();
        System.out.println(name+"方法执行结束了");
    }

    /**
     * 返回通知执行的时候,实际上已经知道目标方法的返回值是什么
     * 这个方法的第二个参数,就是目标方法的返回值
     * 注意第二个方法的参数,这个参数只有在和目标方法的返回值类型相匹配的时候,当前方法才会触发
     * @param jp
     */
    @AfterReturning(value = "pc1()",returning = "val")
    public void afterReturning(JoinPoint jp,Object val){
        String name = jp.getSignature().getName();
        System.out.println(name+"方法执行返回"+val);
    }

    /**
     * 这个是目标方法抛出异常的时候会被触发
     * 当抛出异常的时候,我们希望能够在这个方法中得知发生了什么
     * 注意异常类型
     * @param jp
     */
    @AfterThrowing(value = "pc1()",throwing = "t")
    public void afterThrowing(JoinPoint jp,Throwable t){
        String name = jp.getSignature().getName();
        System.out.println(name+"方法执行抛出"+ t.getMessage());
    }

}

然后把被代理的对象也注册到Spring 容器中:

@Component
public class ICalculatorImpl implements ICalculator {
    @Override
    public int add(int a, int b) {
        System.out.println("(a+b) = " + (a + b));
        return a+b;
    }

    @Override
    public void minus(int a, int b) {
        System.out.println("(a-b) = " + (a - b));
    }
}

加入包扫描:

@Configuration
@ComponentScan
public class JavaConfig {
}

最后,就是从Spring 容器中去获取对象:


public class Demo02 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(JavaConfig.class);
        ICalculator calculator = ctx.getBean(ICalculator.class);
        calculator.add(3,4);
    }
}