【发布时间】:2016-11-17 13:12:03
【问题描述】:
以下代码在 spring 4 中运行良好,但我想知道为什么 getBean(FooService.class) 返回一个已经加载的 bean。我认为无法保证 bean 加载的顺序,这意味着可以获得空 bean。是因为加载目标是一个类而不是字符串(即对象)还是因为 FooService bean 有一个特殊的范围,比如原型?如果是这样,getBean(class)和getBean(object)有什么区别
public abstract class AbstractService implements ApplicationContextAware {
protected ApplicationContext applicationContext;
protected FooService fooService;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@PostConstruct
protected void postConstruct() {
fooService = applicationContext.getBean(FooServiceImpl.class);
}
【问题讨论】:
-
我认为这是春天的感觉,没有得到空对象
-
其实我认为你的bean是null,我的意思是,你使用applicationContext来加载具体的bean对象.有了春天,你就不需要它了。您可以在 bean 参数上使用 @Autowired 注释,或者在 bean 是参数的类构造函数中或在 set 方法中使用更好。