Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting annotated methods using Spring @Configuration and MethodInterceptor

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

like image 761
matafuego Avatar asked Dec 13 '12 14:12

matafuego


1 Answers

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());
    }

}
like image 162
Justin Jose Avatar answered Dec 28 '22 07:12

Justin Jose