Skip to content

Null bean behaviors are different between method getBean(String name) and getBean(Class<T> requiredType ) #33792

Closed as not planned
@felixzhang0818

Description

@felixzhang0818

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 :

public class NullBeanTest {
    @Test
    void test() {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(TestService.class, BeanFactory.class);

        Object obj1 = ctx.getBean("nullableBean");
        assertThat(obj1.getClass().getName()).isEqualTo("org.springframework.beans.factory.support.NullBean");

        Object obj2 = ctx.getBean(NullableBean.class);
        assertThat(obj2.getClass().getName()).isEqualTo("org.springframework.beans.factory.support.NullBean");

        ctx.close();
    }

    @Component
    @Scope("prototype")
    static class TestService {

        @Autowired
        private NullableBean nullableBean;

        public NullableBean getNullableBean() {
            return nullableBean;
        }
    }

    static class NullableBean{

    }

    @Component
    static class BeanFactory {

        @Bean("nullableBean")
        @Scope("prototype")
        public NullableBean create(){
            return null;
        }
    }
}

Asks :
For the null bean, we might have 3 options for the returning of getBean method

  • Option1, directly return null
  • Option2, return the instance of inner null object - org.springframework.beans.factory.support.NullBean
  • Option3, throw exception
  1. From spring framework perspective, what is the official finalized behavior ?
  2. Can we make the behavior consistent in each getBean method and other methods also used for getBean purpose ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: invalidAn issue that we don't feel is valid

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions