spring aop使用

概念

Interceptor VS Advice
Interceptor是Advice中的一种
Advice是AOP编程中某一个方面(Aspect)在某个连接点(JoinPoint)所执行的特定动作,这个连接点(JoinPoint)可以是自定义的;
而Spring中的Interceptor更多关注程序运行时某些特定连接点(属性访问,对象构造,方法调用)时的动作。确切的 说,Interceptor的范围更窄一些。

实现方式

使用DefaultPointcutAdvisor

class TracingInterceptor implements MethodInterceptor {
  Object invoke(MethodInvocation i) throws Throwable {
    System.out.println("method "+i.getMethod()+" is called on "+
                       i.getThis()+" with args "+i.getArguments());
    Object ret=i.proceed();
    System.out.println("method "+i.getMethod()+" returns "+ret);
    return ret;
  }
}

@Configuration
public class InterceptorConfig {

    public static final String traceExecution = "execution(* com.hfi.aop..*.*(..))";
    @Bean
    public DefaultPointcutAdvisor defaultPointcutAdvisor2() {
        TracingInterceptor interceptor = new TracingInterceptor();
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(traceExecution);
 
        // 配置增强类advisor
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        advisor.setPointcut(pointcut);
        advisor.setAdvice(interceptor);
        return advisor;
    }
}

使用@Aspect注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HfiTrace {
    String name() default "默认注解信息";
}

@Component
@Aspect
public class TracingAspect {
    @Before("@annotation(test)")
    public void beforeTest(JoinPoint point, HfiTrace test){
        System.out.println("method " + point.getSignature().getName() + " is called on " + point.getThis() + " with " +"args" + " " + point.getArgs() +"before invoke: "+ test.name());
    }
 
    @AfterReturning(value = "@annotation(test)", returning = "rvt")
    public void afterTest(JoinPoint point, HfiTrace test, Object rvt) {
        System.out.println("method "+point.getSignature().getName() + " returns " + rvt);
        System.out.println("after invoke: " + test.name());
    }

你可能感兴趣的:(spring aop使用)