NikosDim
NikosDim

Reputation: 1508

Run thread in background in spring boot and being able to autowire

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

Answers (1)

art
art

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

Related Questions