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

技术框架:

  • 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,文档注解等)

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

阅读 2.9k
3 个回答

根据你的描述,最有可能的是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);
    }

}

可能性很多,像启动类自己指定扫描的包,profile这些都能导致bean无法被扫描,自己去AbstractApplicationContext debug,确定这些bean是不是都被扫描成元数据了吧

listerner里的类也得让spring管理才能用@Autowired注入其他的bean,用@Component注解一下

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题