spring-projects / spring-projects/spring-framework
Autowiring not working for native applications with prototype components
Nobody has claimed this yet.
- Dominant language
- Java
- Stars
- 60.2k
- Forks
- 38.8k
- Avg merge
- 5d 2h
- Merged PRs (30d)
- 27
Description
If you have a Spring Component with a Scope of "prototype" and the Component has a constructor with some parameters, when that Component is created using BeanFactory in a native application, any Autowired member variables are not populated and no errors are generated. However, the same application run normally works as expected.
To replicate,
- Spring Initialzr to create an project containing "GraalVM Native Support" and "Spring Web"
- Change version of "org.graalvm.buildtools.native" plugin to "1.0.0"
- Create
DemoComponentclass:
@Component
@Scope("prototype")
public class DemoComponent {
@Autowired
public BeanFactory beanFactory;
public DemoComponent(Object obj) {
}
}
- Create
DemoControllerclass:
@RestController
public class DemoController {
@Autowired
protected BeanFactory beanFactory;
@RequestMapping
public void demo() {
DemoComponent demoComponent = beanFactory.getBean(DemoComponent.class, new Object());
System.out.println("HERE1: " + demoComponent.beanFactory);
}
}
- Build using
gradlew bootJar - Generate
reachability-metadata.jsonusingjava -agentlib:native-image-agent=config-output-dir=src\main\resources\META-INF\native-image -jar build\libs\demo-0.0.1-SNAPSHOT.jar - Use browser to go to "http://localhost:8080" and confirm that
beanFactoryofDemoComponentis populated - Build and run native application using
gradlew nativeRun - Use browser to go to "http://localhost:8080" and confirm
beanFactoryofDemoComponentis not populated
Note that if I remove the parameter from the DemoComponent constructor and from the beanFactory.getBean(... line in the DemoController, the beanFactory in the DemoComponent is populated as expected in both native and bootJar.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the DemoComponent and DemoController reproduction, then compare the behavior of bootJar with nativeRun using the generated reachability-metadata.json. The fix is complete when the prototype component's autowired BeanFactory is populated in the native application as it is in the regular run.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java, spring, spring-boot
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100