下面的代码在春季4中工作正常,但我想知道为什么getBean(FooService.class)返回一个已经加载的bean。我认为bean的加载顺序不能保证,这意味着可能会得到一个空bean。这是因为加载目标是一个类而不是一个字符串(即对象)还是因为FooService bean有一个特殊的范围,如原型?如果是这样,是什么的getBean(类)和的getBean(对象)为什么这个bean不为空
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);
}
我认为这是春天的感觉,不得空对象 – XtremeBaumer
其实我认为你的* bean *是** null **,我的意思是,你使用* applicationContext *来加载特定的bean对象。有了春天,你不需要它。您可以在bean参数上使用* @ Autowired *注解,或者在bean是参数的类构造函数中或在* set *方法中更好地使用* @ Autowired *注释。 –