Reputation: 1508
I am trying to build a Spring Boot application that will run a long running thread in the background but the problem I am having is that I cannot autowire spring beans in the thread (at least the way I am doing it)
I have created a repo that shows the problem I am facing
https://github.com/NikosDim/spring-boot-background-thread
In the BackgroundThread class which is my thread I want to be able to autowire objects (look for the //TODO)
Thanks
Nick
Upvotes: 1
Views: 926
Reputation: 1332
You should make BackgroundThread
a prototype bean:
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public BackgroundThread backgroundThreadBean(Dep1 dep1) {
return new BackgroundThread(dep1);
}
Then just inject BackgroundThread
into BackgroundThreadManager
:
@Autowired
private BackgroundThread thread;
If you need to create multiple instances of BackgroundThread
dynamically then ObjectFactory
can be used. Inject factory into BackgroundThreadManager
:
@Autowired
private ObjectFactory<BackgroundThread> backgroundThreadObjectFactory;
and call ObjectFactory.getObject
method to create a new instance of BackgroundThread
.
More info on prototype scope can be found here.
Upvotes: 1