Spring Boot @Autowired 为什么注入为空 ?

作者站长头像
站长
· 阅读数 9

技术框架:

  • Spring-Boot
  • Mybatis-plus

文件路径:org.xxx.modules.message.controller 控制器文件夹org.xxx.modules.message.listener 监听器文件夹(特殊作用文件夹,可以当作放util的)

在控制器中使用 @Autowired 注入 XXXXService(继承了MybatisPlus-IService接口) 可以正常使用。我在 listener 文件夹中的文件也需要用 XXXXService ,但是使用 @Autowiredd 注入的确是 null。

经过排查:

  • 它两都在启动文件的包路径下,不存在找不到。
  • 它两除名字不一样,里面基本没有区别。(Controller用了@RestController,文档注解等)

这是为什么呢?求解,谢谢帮忙的各位(哪怕只是看了一下)。

回复
1个回答
avatar
test
2024-07-11

根据你的描述,最有可能的是listener不是受Spring容器管理的Bean没有被注入到Spring容器中,所以在listener中使用@Autowiredd注入的service为null。一般有两种处理方式,一种是在listener中使用service的时候使用new来创建,另一种是通过SpringContextUtils来获取该service。

@Component
public class SpringContextUtils implements ApplicationContextAware {


    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    /**
     * 通过class获取bean
     *
     * @param clazz bean class
     * @param <T>   class type
     * @return bean
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

}
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容