使用 Spring @Configuration 和 MethodInterceptor 拦截带注释的方法

mat*_*ego 5 spring-aop aopalliance

我需要使用 spring-aop 拦截带注释的方法。我已经有了拦截器,它实现了 AOP 联盟的 MethodInterceptor。

这是代码:

@Configuration
public class MyConfiguration {

    // ...

    @Bean
    public MyInterceptor myInterceptor() {
      return new MyInterceptor();
    }
}
Run Code Online (Sandbox Code Playgroud)
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    // ...
}
Run Code Online (Sandbox Code Playgroud)
public class MyInterceptor implements MethodInterceptor {

    // ...

    @Override
    public Object invoke(final MethodInvocation invocation) throws Throwable {
        //does some stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

从我过去读到的内容来看,我可以使用 @SpringAdvice 注释来指定拦截器何时应该拦截某些东西,但现在已经不存在了。

谁能帮我?

非常感谢!

卢卡斯

mat*_*ego 2

如果有人对此感兴趣......显然这是不可能完成的。为了单独使用 Java(而不是 XML 类),您需要使用带有 @aspect 注释的 AspectJ 和 Spring。

这就是代码的最终结果:

@Aspect
public class MyInterceptor {

    @Pointcut(value = "execution(* *(..))")
    public void anyMethod() {
       // Pointcut for intercepting ANY method.
    }

    @Around("anyMethod() && @annotation(myAnnotation)")
    public Object invoke(final ProceedingJoinPoint pjp, final MyAnnotation myAnnotation) throws Throwable {
        //does some stuff
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

如果其他人发现了不同的内容,请随时发布!

问候,

卢卡斯