2012-12-27 52 views
2

可能重複所有的方法:
@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 * *(..))")
+0

兩天來一直在嘗試不同的切入點,但都沒有工作。將控制器邏輯移至服務層,並僅將自定義註釋保留至服務層。有效。不知道爲什麼如此..任何線索? – amdalal

+0

它不工作,因爲執行的JDK動態代理僅攔截在接口上定義的方法。我假設你的控制器沒有接口(通常他們沒有),所以你的控制器上沒有任何方法被攔截。請參閱http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/aop.html#aop-autoproxy-force-CGLIB – citress

回答

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

您是否在發佈之前嘗試過?我在我的情況下有類似的問題,並且方面從未被執行。我發佈了一個新問題:http://stackoverflow.com/questions/21279716/error-at-0-cant-find-referenced-pointcut-annotation – ftrujillo