一、问题体现
@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);