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", nullMap<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
// this worksassertThat(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.
To elaborate on what Joe reported. There are enough tests failing in Spring Security that it is impractical for us to ignore them. This is making it difficult for us to accept changes into master since we require Spring Framework 5.1.0.BUILD-SNAPSHOT+. If a solution cannot be found soon, can we revert this code until a long term solution can be made? This will allow other projects' tests to pass until the long term solution is found.
I've pushed a change that excludes null beans from ListableBeanFactory.getBeansOfType... which generally makes sense there next to 5.0's getBean behavior. This should fix the immediate HandlerMapping problem (as per a unit test at least) and is likely to be part of the eventual arrangement in any case.
Multi-element injection points (i.e. injected Map / Collection instances aggregating several target beans) do not include null bean entries anymore either now, consistent with the recent getBeansOfType revision.
However, such bean definitions do not disappear completely. They still show up on early type match checks (through isTypeMatch or getBeanNamesForType) and still evaluate late for non-singleton beans, potentially being null in one case but not the other.
For regular injection points that might not resolve uniquely due to an eventally-null bean definition, it is still recommended to use @Primary on the common target bean or to mark the null definition as autowireCandidate=false in general.