Java – how to start the server Daemon in spring
I want to start the daemon mail service thread when the Tomcat server starts So I annotated a method with @ async annotation
I have a class that implements the applicationlistener interface When I call the async method from this class, it does not start asynchronously and block the current thread. When I invoke an asynchronous method from the spring controller class, it will never stop and start asynchronously.
Why did the async method execute successfully from one class instead of another?
What did I do wrong and how do I execute asynchronous methods when the server starts?
Thank you in advance
Editor: Hey, I tried to use the initializingbean interface, @ postconstruct, init method to call my asynchronous method, but it never executed Then I realized that my default lazy init is true, so my lazy init is false and my initializingbean is false Now it executes my asnyc method, but it blocks the current thread. Now there is another problem. What I am facing is that my server does not stop gracefully, but I must forcibly stop my server
Solution
First, you do not need to implement the applicationlistener interface You are using spring - the context of the application is sufficient
Second, you are talking about spring @ async, which means that your task should be started from the application context, and the controller bean is a part of it
You need to make sure you have < comment driver > in your spring XML file
You can start your task in the @ postconstruct function:
@Component public class SampleBeanImpl implements SampleBean { @Async void doSomething() { … } } @Component public class SampleBeanInititalizer { @Autowired private final SampleBean bean; @postconstruct public void initialize() { bean.doSomething(); } }