java - 使用 AspectJ 的日志控制器
问题描述
我有一个 Spring Boot 应用程序,我想记录一些信息,当调用 Controller 方法 id 时会发生什么。
出于某种原因,我的 Aspect 无法正常工作。
这是我用@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 注释来应用代理,而 AspectJ 将代码“编织”到您的应用程序中。简而言之,Spring AOP 可能更容易实现,而 AspectJ 提供了更细粒度的功能(例如编译时编织)。可以在这里找到比较。
我已经从您在帖子中提供的代码片段中尝试了配置。在我添加了几个注释后调用了该建议:
@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");
}
}
推荐阅读
- node.js - Mongoose - 通过特定字段查找文档的子数组
- javascript - Eclipse 2021/03 JavaScript 不支持
- powershell - Powershell Tile Horizontally 仅某些特定窗口
- flutter - 将 json 字符串转换为 json 对象时出错
- c# - 是否应该固定通过 MemoryMarshal.GetReference() 获得的引用?
- permalinks - CSL 参考书目中的固定链接 URL
- java - 将 OneToOne 链接更改为具有另一个 ID 的另一个实体
- javascript - 如何从图像源创建 ipfs 哈希?
- javascript - const 声明需要一个初始化值
- macos - 在 nginx 下运行第二个 vue 应用程序时如何解决空白页?