Closed as not planned
Closed as not planned
Description
Background :
We defined a bean by @bean annotation in method level. Sometimes this method could return null. In the null-returning scenario, when we fetch instance by different getBean method, we found that the behaviors are different.
1, getBean(String name)
It returns a real object instance of "org.springframework.beans.factory.support.NullBean". This is a spring framework inner object.
2, getBean(Class requiredType )
It throws org.springframework.beans.factory.NoSuchBeanDefinitionException
Unit test to reproduce :
public class NullBeanTest {
@Test
void test() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(TestService.class, BeanFactory.class);
Object obj1 = ctx.getBean("nullableBean");
assertThat(obj1.getClass().getName()).isEqualTo("org.springframework.beans.factory.support.NullBean");
Object obj2 = ctx.getBean(NullableBean.class);
assertThat(obj2.getClass().getName()).isEqualTo("org.springframework.beans.factory.support.NullBean");
ctx.close();
}
@Component
@Scope("prototype")
static class TestService {
@Autowired
private NullableBean nullableBean;
public NullableBean getNullableBean() {
return nullableBean;
}
}
static class NullableBean{
}
@Component
static class BeanFactory {
@Bean("nullableBean")
@Scope("prototype")
public NullableBean create(){
return null;
}
}
}
Asks :
For the null bean, we might have 3 options for the returning of getBean method
- Option1, directly return null
- Option2, return the instance of inner null object - org.springframework.beans.factory.support.NullBean
- Option3, throw exception
- From spring framework perspective, what is the official finalized behavior ?
- Can we make the behavior consistent in each getBean method and other methods also used for getBean purpose ?