Skip to content
This repository was archived by the owner on Feb 23, 2023. It is now read-only.
This repository was archived by the owner on Feb 23, 2023. It is now read-only.

Calls to beanFactory.getType() can return null and are not properly guarded #1255

Closed

Description

@ttddyy

Problem

When a FactoryBean resolves its supporting type dynamically, code generation fails with NPE due to beanFactory.getType(beanName) cannot resolve the target type.
This is because the beanFactory used in AOT does not instantiate the factory beans.
If they are instantiated, the BeanFactory#getType() calls FactoryBean#getObjectType() on the target factory's bean instance to resolve its type. However, since it is not instantiated, beanfactory moves on to the next resolution logic looking at the signature of the bean type. If it cannot resolve the type, it returns null and the subsequent AOT logic fails with NPE.

Repro

@SpringBootTest
public class FactoryBeanTest {

    @Autowired
    String str;

    @Autowired
    BeanFactory beanFactory;

    @Test
    void myTest() {
        Class<?> clz = this.beanFactory.getType("foo");
        assertThat(clz).isEqualTo(String.class);

        assertThat(this.str).isEqualTo("HELLO");
    }

    static class MyFactory<T> implements FactoryBean<T> {

        private Class<T> type;
        private T value;

        public MyFactory(Class<T> type, T value) {
            this.type = type;
            this.value = value;
        }

        @Override
        public T getObject() throws Exception {
            return this.value;
        }

        @Override
        public Class<?> getObjectType() {
            return this.type;  // determined by the param in constructor
        }
    }

    @Configuration(proxyBeanMethods = false)
    static class MyConfig {

        @Bean
        FactoryBean<?> foo() {  // NPE due to type=null
//        MyFactory<?> foo() {  // NPE due to type=null
//        FactoryBean<String> foo() {  // OK, type resolved by signature
//        MyFactory<String> foo() {  // OK, type resolved by signature
            return new MyFactory<>(String.class, "HELLO");
        }
    }

}

Stack trace

java.lang.NullPointerException
	at org.springframework.core.annotation.AnnotationsScanner.getDeclaredAnnotations(AnnotationsScanner.java:454)
	at org.springframework.core.annotation.AnnotationsScanner.isKnownEmpty(AnnotationsScanner.java:492)
	at org.springframework.core.annotation.TypeMappedAnnotations.from(TypeMappedAnnotations.java:251)
	at org.springframework.core.annotation.MergedAnnotations.from(MergedAnnotations.java:351)
	at org.springframework.core.annotation.MergedAnnotations.from(MergedAnnotations.java:330)
	at org.springframework.core.annotation.MergedAnnotations.from(MergedAnnotations.java:313)
	at org.springframework.core.annotation.MergedAnnotations.from(MergedAnnotations.java:300)
	at org.springframework.boot.context.AotProxyNativeConfigurationProcessor.lambda$doWithComponents$0(AotProxyNativeConfigurationProcessor.java:59)
	at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
	at org.springframework.boot.context.AotProxyNativeConfigurationProcessor.doWithComponents(AotProxyNativeConfigurationProcessor.java:57)
	at org.springframework.boot.context.AotProxyNativeConfigurationProcessor$Processor.process(AotProxyNativeConfigurationProcessor.java:79)
	at org.springframework.boot.context.AotProxyNativeConfigurationProcessor.process(AotProxyNativeConfigurationProcessor.java:70)
	at org.springframework.aot.context.bootstrap.generator.infrastructure.nativex.NativeConfigurationRegistrar.lambda$processBeanFactory$0(NativeConfigurationRegistrar.java:55)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
	at org.springframework.aot.context.bootstrap.generator.infrastructure.nativex.NativeConfigurationRegistrar.processBeanFactory(NativeConfigurationRegistrar.java:55)
	at org.springframework.aot.context.bootstrap.generator.ApplicationContextAotProcessor.generateBootstrapMethod(ApplicationContextAotProcessor.java:104)
	at org.springframework.aot.context.bootstrap.generator.ApplicationContextAotProcessor.process(ApplicationContextAotProcessor.java:91)
	at org.springframework.aot.test.context.bootstrap.generator.TestContextAotProcessor.generateTestContext(TestContextAotProcessor.java:106)
	at org.springframework.aot.test.context.bootstrap.generator.TestContextAotProcessor.generateTestContexts(TestContextAotProcessor.java:78)
	at org.springframework.aot.test.build.TestContextBootstrapContributor.contribute(TestContextBootstrapContributor.java:61)
	at org.springframework.aot.build.BootstrapCodeGenerator.generate(BootstrapCodeGenerator.java:90)
	at org.springframework.aot.build.BootstrapCodeGenerator.generate(BootstrapCodeGenerator.java:68)
	at org.springframework.aot.test.build.GenerateTestBootstrapCommand.call(GenerateTestBootstrapCommand.java:87)
	at org.springframework.aot.test.build.GenerateTestBootstrapCommand.call(GenerateTestBootstrapCommand.java:45)
	at picocli.CommandLine.executeUserObject(CommandLine.java:1953)
	at picocli.CommandLine.access$1300(CommandLine.java:145)
	at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2352)
	at picocli.CommandLine$RunLast.handle(CommandLine.java:2346)
	at picocli.CommandLine$RunLast.handle(CommandLine.java:2311)
	at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:2179)
	at picocli.CommandLine.execute(CommandLine.java:2078)
	at org.springframework.aot.test.build.GenerateTestBootstrapCommand.main(GenerateTestBootstrapCommand.java:92)
[ERROR]
java.lang.IllegalStateException: Test bootstrap code generator finished with exit code: 1
    at org.springframework.aot.maven.TestGenerateMojo.execute (TestGenerateMojo.java:136)
    ....

The NPE happens at AotProxyNativeConfigurationProcessor.java:59 which has the following lines, and the beanType is null.

Class<?> beanType = beanFactory.getType(beanName);
MergedAnnotation<Component> componentAnnotation = MergedAnnotations.from(beanType).get(Component.class);

Observation

In regular JVM test(no AOT), beanFactory.getType("foo") resolves the bean in the "singleton map" (DefaultSingletonBeanRegistry#singletonObjects).
This is because when ApplicationContext is initialized, it calls ConfigurableListableBeanFactory#preInstantiateSingletons. A part of this method instantiates factory beans. So, the &foo bean is created and registered as a FactoryBean. When BeanFactory#getType is called, getObjectType() method on this factory bean instance is invoked and resolve its supporting type. (String in this example)

However, in AOT code generation, the beanFactory passed to the AotProxyNativeConfigurationProcessor does not instantiate factory beans.
There is no &foo bean in the singleton map when beanFactory.getType is called. Hence, it moves on to the next resolution logic, which checks its parent beanFactory, then the merged bean definition.

When the @Bean is defined as FactoryBean<String>, the detection logic can derive the String from this factory method signature.
However, when the bean is FactoryBean<?>, then the detection logic cannot detect the type and it ends up null.
Therefore, the beanFactory.getType("factory") becomes null and NPE occurs in the subsequent logic.

Suggested Solution

If it is ok to instantiate factory beans while preparing a BeanFactory for AOT transformation, BuildTimeBeanDefinitionsRegistrar#processBeanDefinitions can instantiate factory beans. (sample code)
So that, when beanFactory#getType() is called in a later stage, the resolution logic for FactoryBean works the same as regular application context initiated beanFactory. It calls the target bean instance's FactoryBean#getObjectType to resolve its type.

Activity

  1. added
    status: waiting-for-triage
    on Nov 12, 2021
  2. added a commit that references this issue on Nov 13, 2021
  3. snicoll commented on Nov 17, 2021

    @snicoll
    Contributor

    Thanks @ttddyy, I am working on a different approach for BeanFactory build time preparation that might fix this issue.

  4. snicoll commented on Nov 18, 2021

    @snicoll
    Contributor

    I've noticed that other processors are also calling beanFactory#getBean so we might need to guard them.

  5. self-assigned this
    on Nov 18, 2021
  6. changed the title [-]FactoryBean with wildcards throws NPE in test code generation[/-] [+]Call to beanFactory.getType() can return null and are not properly guarded[/+] on Nov 18, 2021
  7. added
    type: bug
    and removed
    status: waiting-for-triage
    on Nov 18, 2021
  8. added this to the 0.11.0-RC1 milestone on Nov 18, 2021
  9. changed the title [-]Call to beanFactory.getType() can return null and are not properly guarded[/-] [+]Calls to beanFactory.getType() can return null and are not properly guarded[/+] on Nov 18, 2021
  10. added a commit that references this issue on Feb 17, 2024
    803f8b0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

type: bug

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions