I am trying to dynamically register Beans in Spring Boot, however the order of how the beans are created always result in a NoSuchBeanDefinitionException
if it try to autowire one of the dynamic beans.
My setup consists of two projects, one spring-boot-starter project and the actual spring-boot application.
The actual application registers a BeanDefinitionRegistryPostProcessor
that adds the bean definitions. The instances itself are constructed via another bean defined in the starter project that itself takes another bean as dependency.
In order to consume the dynamically registered bean, I created a class annotated with @Component
and defined a constructor expecting said bean as parameter.
When I debug the application by setting @Autowired(required=false)
, I can see that the constructor of my component is called before the dynamic bean has been created. Moreover, not even the factory bean has been created at that time.
Added @DependsOn
with the factory bean's name to component resulted the factory being created first, but not the dynamic beans.
Setting @DependsOn
with the dynamic bean's name works, but that doesn't seem to be the correct way to solve this issue.
Why is Spring creating my beans in the wrong order and what can I do solve this?
EDIT:
I was able to reproduce the issue in a sample repository:
https://github.com/maveeee/spring-dynamic-bean-demo/