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());
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容