Reputation: 147
I want to run a thread in spring application
@Component
public class MyServiceCreationListener {
public void startThread() {
Thread t = new Thread(new MyThread());
t.start();
}
}
Here i used Thread t = new Thread(new MyThread());
This is wrong way.
Please provide solution for this to spring manage MyThread like a spring bean so we can autowire it into other beans and by calling start()
method we can access it
Here is Thread class
@Component
public class MyThread implements Runnable {
public void run() {
System.out.println("Inside run()");
}
}
Upvotes: 3
Views: 11559
Reputation: 2427
By default, spring beans are singleton, but Thread's run
method will only run once. After that it is considered in a state different to RUNNABLE.
So, you need to create a new object every time and you can do that using prototype
scope and ObjectFactory.
Extending Thread
:
@Bean
@Scope("prototype")
public class MyThread implements Runnable {
public void run() {
System.out.println("Inside run()");
}
}
And then:
@Component
public class MyServiceCreationListener {
@Autowired
ObjectFactory<MyThread> myThreadFactory;
public void startThread() {
myThreadFactory.getObject().start();
}
}
This code has not been tested, it just for you to get an idea.
You can find some examples here: Spring and java threads
Upvotes: 5