Reputation: 83
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
Upvotes: 5
Views: 7093
Reputation: 2171
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());
}
}
Upvotes: 4
Reputation: 83
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
Upvotes: 2