AspectJ编译时织入失效:SQL查询性能分析切面未触发
解决AspectJ切面未触发JdbcTemplate方法拦截的问题
问题背景
尝试使用AspectJ实现SQL查询性能分析,定义了针对JdbcTemplate.query*和JdbcTemplate.update*方法的切面,但项目构建部署正常、API可正常工作,唯独切面未触发拦截。
可能的原因及解决方案
1. Pointcut表达式类型不匹配
你的Pointcut使用了call()表达式,它匹配的是调用JdbcTemplate方法的代码位置,而非JdbcTemplate方法本身的执行。若要拦截JdbcTemplate内部方法的执行,需改用execution()表达式:
@Pointcut("(execution(* org.springframework.jdbc.core.JdbcTemplate.query*(..)) || execution(* org.springframework.jdbc.core.JdbcTemplate.update*(..)))") public void profileQuery() { }
- 若坚持使用
call():需要确保调用JdbcTemplate的自定义业务类被AspectJ编织(weave)。 - 若使用
execution():由于JdbcTemplate是第三方库类,需配置AspectJ进行二进制编织,将切面逻辑注入到JdbcTemplate的字节码中。
2. Maven插件配置问题
(1)编译阶段冲突与排除规则问题
当前AspectJ插件绑定到process-classes阶段,但你的maven-compiler-plugin配置了<excludes>**/*.*</exclude>,会排除所有文件的编译,导致AspectJ插件无法找到需要编织的类文件。
调整方案:
- 移除
maven-compiler-plugin中的<excludes>配置:<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <fork>true</fork> <source>${java.version}</source> <target>${java.version}</target> <useIncrementalCompilation>false</useIncrementalCompilation> <!-- 删除excludes节点 --> </configuration> </plugin> - 或者将AspectJ插件的执行阶段改为
compile,确保它在编译时直接处理源码:<executions> <execution> <id>compile</id> <phase>compile</phase> <!-- 修改为compile阶段 --> <goals> <goal>compile</goal> <goal>test-compile</goal> </goals> </execution> </executions>
(2)确认编织日志
你的AspectJ插件配置了<showWeaveInfo>true</showWeaveInfo>,执行mvn clean install时应查看控制台输出,是否有类似如下的编织日志:
[INFO] Weaved into org.springframework.jdbc.core.JdbcTemplate [INFO] Weaved into com.yourpackage.YourServiceClass
如果没有此类日志,说明切面未被成功编织到目标类中,需检查插件配置是否覆盖了正确的类路径。
3. 切面类配置验证
- 确保切面类标记了
@Aspect注解;若使用Spring容器管理,需添加@Component注解,并确保Spring扫描到该类所在的包。 - 若使用纯AspectJ(非Spring AOP),需确保切面类在编译时被AspectJ编译器处理,且包含在编译类路径中。
4. 日志配置排查
检查项目的日志配置文件(如logback.xml、log4j.properties),确保日志级别设置为INFO或更低,否则切面中的logger.info()日志不会输出,导致误以为切面未触发。可临时替换为System.out.println()验证切面是否执行。
验证步骤
- 执行
mvn clean install -X开启debug日志,查看AspectJ插件的执行细节,确认是否有编织动作。 - 反编译
target/classes下的目标类(如业务类或JdbcTemplate),检查是否包含切面逻辑。
内容的提问来源于stack exchange,提问作者Akshay Som
相关产品推荐
相关产品推荐

