2014-10-16 174 views
4

我有一些問題試圖讓我的建議執行。我嘗試了幾個不同的切入點無濟於事。 「@EnableAspectJProxy」似乎在工作,並檢測我的方面。任何建議表示讚賞。Spring Boot AOP

我正在使用spring-boot-aop-starter。

@Aspect 
@Component 
public class ExecutionTimeLogger { 

    private Logger logger; 

    public ExecutionTimeLogger() { 
     logger = LoggerFactory.getLogger(getClass()); 
     logger.info("HEY"); 
    } 

    @Pointcut("within(@org.springframework.stereotype.Controller *)") 
    public void controller() {} 

    @Pointcut("execution(* edu.x.y.z.server.web.controller.*.*(*))") 
    public void methodPointcut() {} 

    @Pointcut("within(@org.springframework.web.bind.annotation.RequestMapping *)") 
    public void requestMapping() {} 

    @Around("controller() && methodPointcut() && requestMapping()") 
    public Object profile(ProceedingJoinPoint pjp) throws Throwable { 
     StopWatch sw = new StopWatch(); 
     String name = pjp.getSignature().getName(); 
     try { 
      sw.start(); 
      return pjp.proceed(); 
     } finally { 
      sw.stop(); 
      logger.info("STOPWATCH: " + sw.getTime() + " - " + name); 
     } 
    } 
} 

我想匹配的是我的包中,並標註有該@RequestMapping註解的方法。我已經嘗試過非常通用的匹配任何和所有方法,沒有任何運氣。

下面是一個方法的樣本有關的意見,應適用於:

@RequestMapping(value = "/analysis", method = RequestMethod.GET) 
@ApiOperation(value = "Get analyses available for the current user") 
JsonModelAndView getAllAnalyses(HttpServletRequest request) 
+0

你期望發生什麼?你有沒有想要被攔截的方法的例子? – 2014-10-17 10:30:48

+0

我希望我的包「edu.x.y.z.server.web.controller」中的方法和用「@RequestMapping」註解的方法被攔截。建議應通過控制檯提供輸出的執行時間和截獲的方法名稱。 – user1595702 2014-10-17 14:29:25

回答

7

我設法解決這個問題。我最終創建了一個小型的Spring應用程序,用特定的切入點來測試用例,以消除其他潛在的障礙。我發現我的切入點需要一些調整。

@Aspect 
@Component 
public class ExecutionTimeLogger { 

    private Logger logger; 

    public ExecutionTimeLogger() { 
     logger = LoggerFactory.getLogger(getClass()); 
     logger.info("HEY"); 
    } 

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)") 
    public void requestMapping() {} 

    @Pointcut("execution(* edu.x.y.z.server.web.controller.*Controller.*(..))") 
    public void methodPointcut() {} 

    @Around("requestMapping() && methodPointcut()") 
    public Object profile(ProceedingJoinPoint pjp) throws Throwable { 
     StopWatch sw = new StopWatch(); 
     String name = pjp.getSignature().getName(); 
     try { 
      sw.start(); 
      return pjp.proceed(); 
     } finally { 
      sw.stop(); 
      logger.info("STOPWATCH: " + sw.getTime() + " - " + name); 
     } 
    } 
} 

正如您所看到的,最大的不同之處在於註釋切入點。

+2

是的,這是一個很大的變化。您的初始嘗試僅在帶有@ @ RequestMapping註解的類中匹配。 – 2014-10-17 18:40:35

2

您可能需要設置proxyTargetClass =真(假設你的控制器沒有一個接口)。使用您自己的@EnableASpectJAutoProxy或設置spring.aop.proxyTargetClass=true

+0

我試圖使用這種方法,但沒有任何運氣。 – user1595702 2014-10-17 14:22:37