Skip to content

Weird behaviour when calling ApplicationContext.getBean() with a null class reference #23045

Closed

Description

@stsypanov

I've run into wierd behaviour when calling ApplicationContext::getBean for nullable class:

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);

        Class o = null;
        Object bean = context.getBean(o);//todo should be NPE
    }
}

Execution of this method throws exception with list of all beans in the context

Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'java.lang.Object' available: more than one 'primary' bean found among candidates: [org.springframework.context.annotation.internalConfigurationAnnotationProcessor, org.springframework.context.annotation.internalAutowiredAnnotationProcessor, org.springframework.context.annotation.internalCommonAnnotationProcessor, org.springframework.context.event.internalEventListenerProcessor, org.springframework.context.event.internalEventListenerFactory, demoApplication, org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory, org.springframework.boot.autoconfigure.AutoConfigurationPackages, org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration, org.springframework.boot.autoconfigure.condition.BeanTypeRegistry, propertySourcesPlaceholderConfigurer, org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration$TomcatWebSocketConfiguration, websocketServletWebServerCustomizer, org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat, tomcatServletWebServerFactory, org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration, servletWebServerFactoryCustomizer, tomcatServletWebServerFactoryCustomizer, server-org.springframework.boot.autoconfigure.web.ServerProperties, org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor, org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata, webServerFactoryCustomizerBeanPostProcessor, errorPageRegistrarBeanPostProcessor, org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletConfiguration, dispatcherServlet, spring.http-org.springframework.boot.autoconfigure.http.HttpProperties, spring.mvc-org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties, org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration, dispatcherServletRegistration, org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration, org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration, taskExecutorBuilder, applicationTaskExecutor, spring.task.execution-org.springframework.boot.autoconfigure.task.TaskExecutionProperties, org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration, defaultValidator, methodValidationPostProcessor, org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration, error, beanNameViewResolver, org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration, conventionErrorViewResolver, org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration, errorAttributes, basicErrorController, errorPageCustomizer, preserveErrorControllerTargetClassPostProcessor, spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties, org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration, faviconHandlerMapping, faviconRequestHandler, org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration, requestMappingHandlerAdapter, requestMappingHandlerMapping, mvcConversionService, mvcValidator, mvcContentNegotiationManager, mvcPathMatcher, mvcUrlPathHelper, viewControllerHandlerMapping, beanNameHandlerMapping, resourceHandlerMapping, mvcResourceUrlProvider, defaultServletHandlerMapping, mvcUriComponentsContributor, httpRequestHandlerAdapter, simpleControllerHandlerAdapter, handlerExceptionResolver, mvcViewResolver, mvcHandlerMappingIntrospector, org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter, defaultViewResolver, viewResolver, welcomePageHandlerMapping, requestContextFilter, org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration, hiddenHttpMethodFilter, formContentFilter, org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration, mbeanExporter, objectNamingStrategy, mbeanServer, org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration, springApplicationAdminRegistrar, org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration, org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration, standardJacksonObjectMapperBuilderCustomizer, spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties, org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration, jacksonObjectMapperBuilder, org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration, parameterNamesModule, org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration, jacksonObjectMapper, org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration, jsonComponentModule, org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration, stringHttpMessageConverter, org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration, mappingJackson2HttpMessageConverter, org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration, org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration, messageConverters, org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration$LoggingCodecConfiguration, loggingCodecCustomizer, org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration$JacksonCodecConfiguration, jacksonCodecCustomizer, org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration, org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration, spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties, org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration, taskSchedulerBuilder, spring.task.scheduling-org.springframework.boot.autoconfigure.task.TaskSchedulingProperties, org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration, restTemplateBuilder, org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration$TomcatWebServerFactoryCustomizerConfiguration, tomcatWebServerFactoryCustomizer, org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration, characterEncodingFilter, localeCharsetMappingsCustomizer, org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration, multipartConfigElement, multipartResolver, spring.servlet.multipart-org.springframework.boot.autoconfigure.web.servlet.MultipartProperties, autoConfigurationReport, org.springframework.boot.context.ContextIdApplicationContextInitializer$ContextId, springApplicationArguments, springBootBanner, springBootLoggingSystem, environment, systemProperties, systemEnvironment, org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry, messageSource, applicationEventMulticaster, servletContext, contextParameters, contextAttributes, lifecycleProcessor]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.determinePrimaryCandidate(DefaultListableBeanFactory.java:1529)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1128)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveBean(DefaultListableBeanFactory.java:407)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:341)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:335)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1123)
	at com.example.demo.DemoApplication.main(DemoApplication.java:14)

Shouldn't we throw NPE immediately when one instantiates ResolvableType with nullable field type instead of checking all beans in the context?

Activity

  1. added
    status: waiting-for-triage
    on May 28, 2019
  2. added
    in: core
    on May 28, 2019
  3. sbrannen commented on May 28, 2019

    @sbrannen
    Member

    Well, the Javadoc for org.springframework.core.ResolvableType.forRawClass(Class<?>) states the following.

    clazz the class to introspect (null is semantically equivalent to Object.class for typical use cases here)

    Though I do agree that attempting to look up beans of type java.lang.Object for this particular use case is probably not what the user intended.

    I propose that we add a specific not-null assertion for the Class<T> requiredType argument. After all, it's not annotated with @Nullable. So null should not be supported.

    Another option would be to add the following instead of a not-null assertion.

    if (requiredType == null) {
    	throw new NoSuchBeanDefinitionException(requiredType);
    }

    @jhoeller, what do you think about the above proposals?

  4. removed
    status: waiting-for-triage
    on May 28, 2019
  5. self-assigned this
    on May 28, 2019
  6. added this to the 5.2 M3 milestone on May 28, 2019
  7. stsypanov commented on May 28, 2019

    @stsypanov
    ContributorAuthor

    I strongly like

    if (requiredType == null) {
      throw new NoSuchBeanDefinitionException(requiredType);
    }
    

    it's easier to understand than plain NPE.

  8. added
    type: enhancement
    on May 28, 2019
  9. changed the title [-]Wierd behaviour when calling `ApplicationContext::getBean` for nullable class[/-] [+]Weird behaviour when calling `ApplicationContext.getBean()` with a null class reference[/+] on May 28, 2019
  10. added
    status: pending-design-work
    and removed on Jun 3, 2019
  11. sbrannen commented on Jun 3, 2019

    @sbrannen
    Member

    In 4.3.x, the corresponding code path throws an IllegalArgumentException for a null requiredType:

    https://github.com/spring-projects/spring-framework/blob/4.3.x/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java#L994

    Consequently, I now propose that we simply reinstate the original behavior here (treating this effectively as a minor regression) by adding an explicit Assert.notNull(...) in 5.0.x, 5.1.x, and master (5.2.x). We should also update the Javadoc accordingly.

  12. added
    type: regression
    and removed
    type: enhancement
    status: pending-design-work
    on Jun 3, 2019
  13. modified the milestones: 5.2 M3, 5.1.8 on Jun 4, 2019
  14. sbrannen commented on Jun 4, 2019

    @sbrannen
    Member

    Design Decisions

    Add explicit Assert.notNull(...) checks for the requiredType in 5.1.x and master as appropriate for:

    • getBean(Class<T> requiredType, Object... args)
    • getBeanProvider(Class<T> requiredType)
    • resolveNamedBean(Class<T> requiredType)
  15. added a commit that references this issue on Jun 4, 2019
    6eac141
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

in: coretype: regression

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions