我有一个 Spring boot 应用程序,我想记录一些信息,当调用 Controller 方法 id 时会发生什么情况。
由于某种原因,我的方面无法正常工作。
这是我用 @Aspect 注释的 @Component 类:
@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controller() {
}
@Pointcut("execution(* *.*(..))")
protected void allMethod() {
}
@Before("controller()&& allMethod()")
public void logBefore(JoinPoint joinPoint) {
}
当使用 REST 调用任何 Controller 方法时,不会调用 logBefore 方法。
最佳答案
重要提示:正如您所说,您正在使用 Spring Boot 设置,我的假设是您已经实现了 Spring AOP 模块而不是“实际的”AspectJ 库。差异很大,因为它们之间的 AOP 实现不同。 Spring使用AspectJ注解来应用proxying ,而 AspectJ 将代码“编织”到您的应用程序中。简而言之,Spring AOP 可能更容易实现,而 AspectJ 提供更细粒度的功能(例如编译时编织)。对比可以查here .
我已经尝试了您在帖子中提供的代码片段中的配置。在我添加了几个注释后,该建议被调用:
@SpringBootApplication
// Be sure to add EnableAspectJAutoProxy and set proxyTargetClass to true
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class DemoApplication {
...
}
// Be sure to add @Aspect and @Component
@Component
@Aspect
public class DemoAop {
private static Logger logger = LoggerFactory.getLogger(DemoAop.class);
@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controller() {
}
@Pointcut("execution(* *.*(..))")
protected void allMethod() {
}
@Before("controller()&& allMethod()")
public void logBefore(JoinPoint joinPoint) {
logger.info("TEST");
}
}
关于java - 使用 AspectJ 的日志 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55942171/