SpringBoot自行new出的对象中的成员变量不能使用@Autowired注入的解决办法

一、问题体现

  @Autowired
  private PlantService plantService;

运行此Service所提供的方法后报异常提示:plantService 为 null

二、问题原因

自己创建的类未使用(@Component)即为加入Spring容器中,则其中的被@Autowired的成员变量也不会被注入。

三、解决办法

不使用@Autowired,而使用一个自定义工具类帮助注入

第一步:创建工具类并使用@Component注解注入
此处可能报applicationContext为null的错误
解决办法:将此工具类放在Application启动类同一个包下

@Component
public class GetBeanUtil implements ApplicationContextAware  {
    protected static ApplicationContext applicationContext ;

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        if (applicationContext == null) {
            applicationContext = arg0;
        }

    }
    public static Object getBean(String name) {
        //name表示其他要注入的注解name名
        return applicationContext.getBean(name);
    }
    /**
     * 拿到ApplicationContext对象实例后就可以手动获取Bean的注入实例对象
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
}

第二步:
在需要注入的成员变量位置使用工具类赋值

private PlantService plantService = GetBeanUtil.getBean(PlantService.class);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容