写了一个工具类,并且使用
Spring
注入了一个Service
但是使用的时候返回null
。
分析
- 如果是找不到类应该在启动的时候报错,但是知道运行时才报空指针(@Autowired默认required = true)
- spring是在启动的时候扫描文件,将相应注解的
bean
保存,然后再统一注入 - 我的工具类是使用反射生成的实例,所以新的实例中没有注入的
bean
解决
public class BeanFactoryTest implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
}
手动获取bean
BlogService blogService=beanFactoryTest.getApplicationContext().getBean(BlogService.class);
其它
使用注入的类如果不是spring管理的注入也没有效果,即只有在bean
中才能使用bean