Question

I need to intercept annotated methods using spring-aop. I already have the interceptor, it implements MethodInterceptor from AOP Alliance.

Here is the code:

@Configuration
public class MyConfiguration {

    // ...

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

    // ...

    @Override
    public Object invoke(final MethodInvocation invocation) throws Throwable {
        //does some stuff
    }
}

From what I've been reading it used to be that I could use a @SpringAdvice annotation to specify when the interceptor should intercept something, but that no longer exists.

Can anyone help me?

Thanks a lot!

Lucas

Was it helpful?

Solution 2

In case anyone is interested in this... apparently this can't be done. In order to use Java solely (and no XML class) you need to use AspectJ and Spring with @aspect annotations.

This is how the code ended up:

@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
        ...
    }
}

If anyone else finds out something different please feel free to post it!

Regards,

Lucas

OTHER TIPS

MethodInterceptor can be invoked by registering a Advisor bean as shown below.

@Configurable
@ComponentScan("com.package.to.scan")
public class AopAllianceApplicationContext {    

    @Bean
    public Advisor advisor() {
       AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();    
       pointcut.setExpression("@annotation(com.package.annotation.MyAnnotation)");
       return new DefaultPointcutAdvisor(pointcut, new MyInterceptor());
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top