2014-10-16 177 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