How to solve springboot CommandLineRunner run not called problem?
1. The purpose of this post
When we use CommandLineRunner in springboot applications, we expect its run to be called when the app starts. But , sometimes the run is not called even if the code and the settings is both ok.
This article would help you to debug and solve this issue.
2. Environments
SpringBoot 1.x or 2.x
Java 1.8+
3. The problem code
3.1 pom.xml
This is the pom.xml content:
3.2 Runner1.java and Runner2.java
There are two CommandLineRunners in this project:
Now everything works fine:
But after we add a new Runner3.java, runner1 and runner2 stop working.
3.3 Adding Runner3.java to cause the problem
In Runner3.java, we setup a lock to cause the current thread to be blocked. Then we can see what happens next:
The runner1 and runner2 call log is not printed, why?
3.4 The reason
All the problem is caused by the @PostConstruct annotation. The Runner3 is a Runnable, but it’s not called as a thread, but as a normal method. And because the springboot starter thread is blocked by Runner3, so runner1 and runner2 can not get the attention.
3.5 How to solve it
Comment out the @PostConstruct, and start it with a Thread, then everything works fine:
And start runner3 in Runner2
Then we get this:
The example source code has been uploaded to github, you can visit here to view the example source codes.