Skip to content

Consistent non-exposure of null beans in the BeanFactory API [SPR-17034] #21572

Closed
@spring-projects-issues

Description

@spring-projects-issues

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:

Issue Links:

Referenced from: commits 77d72f1, 680afa7, def6fbb

0 votes, 6 watchers

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions