Description
Brian Clozel opened SPR-17034 and commented
Currently the core container allows to create null beans like this:
@Bean
public HandlerMapping myHandlerMapping() {
return null;
}
This can be quite useful to back off and consume resources if that bean is not required (or a no-op), given the application configuration.
A recent change in the Spring MVC infrastructure setup uncovered several issues, since in many places we're asking for those infrastructure beans without guarding against null values.
Given the previous myHandlerMapping
bean declaration, asking BeanFactory
for beans can then return null
instances in several cases:
// the map will contain "myHandlerMapping", null
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
// this works
assertThat(context.getBean("resourceHandlerMapping")).isEqualTo(null);
/*
* this throws org.springframework.beans.factory.BeanNotOfRequiredTypeException:
* Bean named 'resourceHandlerMapping' is expected to be of type
* 'org.springframework.web.servlet.HandlerMapping' but was actually of type
* 'org.springframework.beans.factory.support.NullBean'
*/
assertThat(context.getBean("resourceHandlerMapping", HandlerMapping.class)).isEqualTo(null);
Looking at the previous examples, we could improve the consistency of the behavior, or document a bit more the null case and what it means.
Affects: 5.0.7
Reference URL: a40d25a
Attachments:
- DispatcherServlet-5.0.7.BUILD-SNAPSHOT.png (97.57 kB)
- DispatcherServlet-5.1.0.BUILD-SNAPSHOT.png (87.17 kB)
Issue Links:
- CastClass exception when wiring Map of beans (NullBean instead of 'null' in the map) [SPR-16033] #20582 CastClass exception when wiring Map of beans (NullBean instead of 'null' in the map)
- CastClass exception (NullBean instead of 'null' value) when getting map of beans directly from ApplicationContext [SPR-16163] #20711 CastClass exception (NullBean instead of 'null' value) when getting map of beans directly from ApplicationContext
- ObjectProvider iterable/stream access for "beans of type" resolution in @Bean methods [SPR-11419] #16046 ObjectProvider iterable/stream access for "beans of type" resolution in
@Bean
methods - Autowire contract is not honored in cases where FactoryBean or @Bean return null [SPR-15829] #20384 Autowire contract is not honored in cases where FactoryBean or
@Bean
return null - WebSocketConfigurationSupport.defaultSockJsTaskScheduler adds NoOpScheduler to context that is not usable in any way [SPR-16189] #20737 WebSocketConfigurationSupport.defaultSockJsTaskScheduler adds NoOpScheduler to context that is not usable in any way
- Support for autowire-candidate with @Bean [SPR-16204] #20752 Support for autowire-candidate with
@Bean
- Support for null bean in functional bean registration [SPR-17057] #21595 Support for null bean in functional bean registration
Referenced from: commits 77d72f1, 680afa7, def6fbb
0 votes, 6 watchers