切入点将所有方法与自定义注释匹配

时间:2012-12-27 15:43:40

标签: aop aspectj spring-aop spring-annotations

  

可能重复:
  @AspectJ pointcut for all methods of a class with specific annotation

我正在尝试为具有自定义注释的类的所有方法编写切入点。这是代码

  • 注释:

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Retention(value = RetentionPolicy.RUNTIME)
    @Target(value = ElementType.METHOD)
    public @interface ValidateRequest {}
    
  • 控制器中的方法:

     @RequestMapping(value = "getAbyB", produces = "application/json")
     @ResponseBody
     @ValidateRequest
     public Object getAbyB(@RequestBody GetAbyBRequest req) throws Exception { 
         /// logic
     }
    
  • 方面:

     @Aspect
     @Component
     public class CustomAspectHandler {
         @Before("execution(public * *(..))")
         public void foo(JoinPoint joinPoint) throws Throwable {
             LOG.info("yippee!");
         }
     }
    
  • 的applicationContext:

    `<aop:aspectj-autoproxy />`
    

我一直在尝试下面提到的各种建议,但似乎没有任何建议(除了上面使用的建议外)

  • @Around("@within(com.pack.Anno1) || @annotation(com.pack.Anno1)")
  • @Around("execution(@com.pack.Anno1 * *(..))")

1 个答案:

答案 0 :(得分:2)

这应该有效:

 @Aspect
 @Component
 public class CustomAspectHandler {
    @Pointcut("execution(@ValidateRequest * *.*(..))")
    public void validateRequestTargets(){}

     @Around("validateRequestTargets()")
     public Object foo(JoinPoint joinPoint) throws Throwable {
         LOG.info("yippee!");
         return joinPoint.proceed();
     }
 }