When using CommandLineRunner in Spring Boot applications, we expect its run method to be called when the application starts. However, sometimes the run method is not called, even if the code and settings appear correct.
This article will help you debug and resolve this issue.
2. Environments
Spring Boot 1.x or 2.x
Java 1.8+
3. The problem code
3.1 pom.xml
The following is the pom.xml content:
3.2 Runner1.java and Runner2.java
There are two CommandLineRunner implementations in this project:
Initially, everything works fine:
However, after adding Runner3.java, Runner1 and Runner2 stop working.
3.3 Adding Runner3.java to cause the problem
In Runner3.java, we set up a lock to block the current thread. The result is:
The logs for Runner1 and Runner2 are not printed. Why?
3.4 The reason
The issue is caused by the @PostConstruct annotation. Runner3 is a Runnable, but it is not executed as a thread. Instead, it runs as a normal method, blocking the Spring Boot starter thread. As a result, Runner1 and Runner2 cannot execute.
3.5 How to resolve it
To fix the issue, remove the @PostConstruct annotation and start Runner3 in a separate thread. Here’s the corrected code:
Start Runner3 in Runner2:
Now, the logs show all runners working correctly:
4. Summary
In this post, we explored why the CommandLineRunner’s run method might not be called in a Spring Boot application. The issue was caused by a blocking operation in a @PostConstruct method, which prevented other runners from executing. By moving the blocking operation to a separate thread, we resolved the issue and ensured all runners worked as expected.
My intention with this article was to help others who might be considering solving such a problem.
So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by
email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope: