2012-12-13 196 views
2

我需要使用spring-aop拦截带注释的方法。 我已经有了拦截器,它实现了AOP联盟的MethodInterceptor。使用Spring @Configuration和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批注指定当拦截器拦截要的东西,但不再存在。

任何人都可以帮助我吗?

非常感谢!

卢卡斯

回答

1

如果有人有兴趣在这......显然这无法做到的。 为了单独使用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 
     ... 
    } 
} 

如果别人发现了一些不同的东西,请随意张贴了!

问候,

卢卡斯

0

MethodInterceptor可以通过如下所示注册Advisor豆被调用。

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

} 
相关问题