You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
We used to return null from getBean(name) before Spring Framework 5.0 there but tightened this as part of our null-safety efforts. This behavior has been in place for several years already, so we do not intend to revisit it at this point.
The reason for the different behavior is that a null bean is not of the specified required type, so not encountered as a match by getBean(type). Note that getBean(type) is effectively a type-matching retrieval method, a sort of simple version of getBeansOfType, whereas getBean(name) is a straight lookup by id. In Spring, beans are always registered by name; the type is a secondary characteristic that can be used for retrieval but does not identify a specific bean.
In practice, avoid null beans wherever you can. You might be able to conditionally register a bean instead. Pretending a bean is defined but then returning null from its factory method was always a fragile arrangement, and as of Spring Framework 5.0 we do not consider this first class anymore. We rather just tolerate it for some degree of backwards compatibility with such factory methods in existing application code. Consistent behavior is not a goal there, just tolerance of certain arrangements.
Uh oh!
There was an error while loading. Please reload this page.
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 :
Asks :
For the null bean, we might have 3 options for the returning of getBean method
The text was updated successfully, but these errors were encountered: