Affects: Spring Framework 5.2.9.RELEASE


We are upgrading from Spring 4 to Spring 5 and encountered java.lang.ClassCastException: class org.springframework.beans.factory.support.NullBean cannot be cast to class XXX when one of our bean configured to use method injection where the injected bean is constructed from a factory method which is possible to return null.

Considering the following example code:

@Configuration
public class Testing {

    public static class MyObject {
    }

    public static interface MyInterface {
        MyObject getFoo();
    }

    public static class MyInterfaceImpl implements MyInterface {
        private MyObject foo;
        @Override
        public MyObject getFoo() {
            return foo;
        }
        public void setFoo(MyObject foo) {
            this.foo = foo;
        }
    }

    @Component("myInterfaceImpl2")
    public static interface MyInterface2 extends MyInterface {
        @Lookup("myObject")
        @Override
        MyObject getFoo();
    }

    @Bean("myObject")
    public MyObject myObject() {
        return null;
    }

    @Bean("myInterfaceImpl1")
    public MyInterface myInterfaceImpl1(MyObject myObject) {
        MyInterfaceImpl myInterfaceImpl1 = new MyInterfaceImpl();
        myInterfaceImpl1.setFoo(myObject);
        return myInterfaceImpl1;
    }

    public static void main(String[] args) {
        try (AbstractApplicationContext applicationContext = new AnnotationConfigApplicationContext("com.github.sammyhk.test")) {
            for (String beanName : Arrays.asList("myInterfaceImpl1", "myInterfaceImpl2")) {
                MyInterface myInterfaceImpl = applicationContext.getBean(beanName, MyInterface.class);
                MyObject myObject = myInterfaceImpl.getFoo();
                System.out.println(beanName + ": " + myObject);
            }
        }
    }
}

The above code will output:

myInterfaceImpl1: null
Exception in thread "main" java.lang.ClassCastException: class org.springframework.beans.factory.support.NullBean cannot be cast to class XXX$MyObject

Suspected this should be a bug because traditional bean injection do not provide org.springframework.beans.factory.support.NullBean, only method injection encountered this issue.