我需要使用spring-aop截取带注释的方法。我已经有了拦截器,它实现了来自AOP Alliance的MethodInterceptor。
代码如下:
@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
}
}
根据我过去所读到的,我可以使用@SpringAdvice注解来指定拦截器何时应该拦截某些东西,但这种情况已经不存在了。
有谁可以帮我?
非常感谢!
卢卡斯
发布于 2012-12-17 21:59:34
如果有人对此感兴趣的话...显然,这是不可能做到的。为了单独使用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
...
}
}
如果其他人发现了什么不同的东西,请随时张贴!
致以敬意,
卢卡斯
发布于 2017-03-19 14:11:07
可以通过注册Advisor
bean来调用MethodInterceptor
,如下所示。
@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());
}
}
https://stackoverflow.com/questions/13862216
复制相似问题