SpringBoot 2.6.2集成AspectJ与Spring AOP时Autowired注入空指针求助
解决AspectJ切面中@Autowired注入空指针的思路
核心原因
你碰到的问题本质是原生AspectJ切面不受Spring容器管理,Spring的依赖注入机制无法作用于它,所以@Autowired标注的MyUtility会出现空指针。因为AspectJ是编译/加载期织入逻辑,切面类是被直接实例化执行的,并非由Spring创建的Bean。
具体解决步骤
1. 明确切面的管理方式
- 如果
OtherAspect是Spring AOP切面:给类加上@Component和@Aspect注解,让Spring将其纳入容器管理,这样依赖注入会自动生效。注意Spring AOP仅支持拦截Spring Bean的方法,无法处理非Bean类的方法。 - 如果
OtherAspect是原生AspectJ切面:不能依赖Spring的@Autowired,换用以下方式获取依赖:- 通过Spring上下文工具类手动获取Bean:
然后在切面中调用:import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) { SpringContextHolder.context = applicationContext; } public static <T> T getBean(Class<T> beanClass) { return context.getBean(beanClass); } }MyUtility myUtility = SpringContextHolder.getBean(MyUtility.class); - 若
MyUtility是普通工具类,也可以在切面的初始化方法中手动实例化它。
- 通过Spring上下文工具类手动获取Bean:
2. 检查aop.xml配置
如果希望Spring管理OtherAspect,不要在aop.xml中将其配置为纯AspectJ切面,仅靠@Aspect和@Component注解即可让Spring接管。
3. 验证织入方式
- 检查
aspectj-maven-plugin的配置,明确织入范围:如果是编译期织入,确保切面类被正确织入,但Spring Bean的切面优先使用Spring AOP动态代理(JDK或CGLIB),避免两种织入方式冲突。 - 需Spring管理的切面,不要用AspectJ织入,依赖Spring AOP的代理机制即可。
4. 确认MyUtility的Bean定义
确保MyUtility类上标注了@Component(或其他Spring Bean注解),且启动类的@ComponentScan覆盖了该类所在的包,保证它被Spring扫描并创建为Bean。
5. 排查切面实例化来源
可以打印OtherAspect的this对象哈希值,对比Spring容器中该Bean的哈希值,判断切面是否是由Spring创建的实例——如果哈希值不一致,说明切面是被AspectJ自动实例化的,Spring的依赖注入自然不会生效。
内容的提问来源于stack exchange,提问作者bkqdad
相关产品推荐
相关产品推荐

