Tiina Tiina - 10 months ago 42
Java Question

why this bean is not null

The following code works fine in spring 4, but I am wondering why the getBean(FooService.class) returns an already-loaded bean. I thought the sequence of bean loading is not guaranteed, meaning that it is possible to get a null bean. Is it because the loading target is a class not a String (ie. object) or is it because the FooService bean has a special scope, like prototype? If so, what is the difference between getBean(class) and getBean(object)

public abstract class AbstractService implements ApplicationContextAware {
protected ApplicationContext applicationContext;

protected FooService fooService;

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;

protected void postConstruct() {
fooService = applicationContext.getBean(FooServiceImpl.class);

Answer Source

For starters, String is a full rights class, like any you can create yourself.

The reason you're getting something in fooService, is that the ApplicationContext getBean method is able to retrieve a managed bean according to the argument you're passing to it.

If it weren't possible to retrieve the bean, you could get some of these exceptions:

Throws: NoSuchBeanDefinitionException - if no bean of the given type was found NoUniqueBeanDefinitionException - if more than one bean of the given type was found BeansException - if the bean could not be created