自定义Spring注解未生效求助:标注方法无执行无日志
问题分析与解决
兄弟,你遇到的这个坑我之前刚踩过!先给你拍板:是的,必须引入Spring AOP依赖,不然Spring根本识别不了你的切面逻辑。而且你的切面代码还有个致命小问题,得一起修正,不然就算引入依赖也不一定正常工作。
1. 先补全AOP依赖
Spring AOP的功能不是核心包自带的,必须单独引入依赖:
- 如果是Maven项目,在
pom.xml里加:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> - 如果是Gradle项目,在
build.gradle里加:implementation 'org.springframework.boot:spring-boot-starter-aop'
这个依赖会自动帮你配置AspectJ相关的Bean,开启切面的自动代理功能。
2. 修复你的切面代码
你的@Around方法里漏掉了最关键的一步:调用proceedingJoinPoint.proceed()!没这行代码,被注解的目标方法根本不会执行,而且你的切面逻辑只跑了日志就直接终止了。另外建议把注解的全类路径写上,避免同名注解冲突。
修正后的代码:
@Aspect @Component public class LethargicLoggerAspect { private final Logger log = LoggerFactory.getLogger(getClass()); // 这里要替换成你自己的LethargicLogger注解的包路径 @Around("@annotation(com.yourproject.annotation.LethargicLogger)") public Object logSlowExecutionTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { log.error("HIIIIIIIIII..."); // 必须调用proceed(),触发目标方法执行 Object result = proceedingJoinPoint.proceed(); // 也可以在这里加后置日志,比如记录方法完成信息 log.error("Method [{}] finished execution", proceedingJoinPoint.getSignature().getName()); return result; } }
3. 检查自定义注解的定义
确保你的LethargicLogger注解加上了正确的元注解,不然Spring在运行时识别不了它:
@Target(ElementType.METHOD) // 指定注解只能用在方法上 @Retention(RetentionPolicy.RUNTIME) // 让注解在运行时能被Spring读取到 public @interface LethargicLogger { // 可以根据需求加参数,比如慢方法的时间阈值之类的 }
4. 最后检查Spring的扫描配置
- 如果是Spring Boot项目,主启动类的
@SpringBootApplication已经包含了@ComponentScan,但要确保你的切面类和自定义注解在主启动类的包或子包下,不然要手动在主启动类上加@ComponentScan(basePackages = {"com.yourproject.aspect", "com.yourproject.annotation"})指定扫描路径。 - 如果是传统Spring项目,要在配置类上加
@EnableAspectJAutoProxy来开启AOP代理功能。
按上面的步骤改完,你的注解切面应该就能正常触发日志输出了!
内容的提问来源于stack exchange,提问作者Ron Stevenson
相关产品推荐
相关产品推荐

