Spring Boot AOP

use*_*702 4 java spring-aop spring-boot

我有一些问题试图让我的建议执行.我尝试了几个不同的切入点无济于事."@EnableAspectJProxy"似乎正在工作并检测我的方面.任何建议表示赞赏.

我正在使用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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试匹配我的包中的任何方法,并使用@RequestMapping注释进行注释.我已经尝试了非常通用的匹配任何和所有方法,没有任何运气.

以下是应将建议应用于的方法示例:

@RequestMapping(value = "/analysis", method = RequestMethod.GET)
@ApiOperation(value = "Get analyses available for the current user")
JsonModelAndView getAllAnalyses(HttpServletRequest request)
Run Code Online (Sandbox Code Playgroud)

use*_*702 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的那样,最大的区别在于注释切入点.

  • 是的,这是一个很大的变化.您的初始尝试仅在具有`@RequestMapping`注释的类中匹配. (2认同)