Test: node2800""answers_question How to run a job automatically after Spring boot start | TechScreen Revised

How to run a job automatically after Spring boot start

In a normal Spring MVC environment one of the to start a job automatically is define a class in the web.xml which will be initiated after the spring context is load. One of the advantages of the spring boot is that is does not need any XML file configuration which makes many developers life easier. Spring boot also provides the annotation @Async for the use asynchronous methods. However for cases that you need to migrate from one framework to spring boot, it will be necessary to keep the the method in the traditional way e.g Threads. So this bring us to the point: What has to be done then to run a job automatically with spring boot since the tool does not use any xml file config? Spring boot provides some methods that are fired during the application start up, this could be the solution for the problem but there is a small issue on that : The methods e.g. @PostContruct fired during the start up are fired before the context is complete loaded that means your "job class" will start but all its dependencies will not be fired -null- in another words; everything with the annotation @Autowired will be now because when you created the instance too early. How can we instantiate automatically the a job Class or Thread and all its dependencies after the spring boot context is load ?
1 answer

Use ContextRefreshedEvent

Spring boot provides some classes that can be fired at events. One of these events is ContextRefreshedEvent so, whenever your context is changed e.g. Application start up this event will be fired.

The event also contains the Application Context which you can use to get the beans of your class.
public class ApplicationStartup implements ApplicationListener {
public void onApplicationEvent(final ContextRefreshedEvent event) {
// here your code ... e.g. event.getApplicationContext();

Once you have the Application Context, you can start your job class and get the beans from the Context.
The job will start normally with all its dependency correctly instantiated.