background

In the actual development of Spring Boot projects, we sometimes need to load some data or pre-complete some actions when the project services start up. To solve this problem, Spring Boot provides a way to implement this requirement by implementing the interface CommandLineRunner.

implementation

Implementation: Only one class is required and no additional configuration is required.

Implementation steps:

1. Create a class MyStartupRunnerTest that implements the interface CommandLineRunner

package com.energy; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * Created by CavanLiu on 2017/2/28 0028. */ @Component @Order(value=1) public class MyStartupRunnerTest implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(">>>>This is MyStartupRunnerTest Order=1. Only testing CommandLineRunner... < < < < "); } } @Order(value=1) public class MyStartupRunnerTest implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(">>>>This is MyStartupRunnerTest Order=1. Only testing CommandLineRunner... < < < < "); }}Copy the code

2. Create a class MyStartupRunnerTest2 that implements the interface CommandLineRunner

package com.energy; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * Created by CavanLiu on 2017/2/28 0028. */ @Component @Order(value=2) public class MyStartupRunnerTest2 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(">>>>This is MyStartupRunnerTest Order=2. Only testing CommandLineRunner... < < < < "); } } @Order(value=2) public class MyStartupRunnerTest2 implements CommandLineRunner { @Override public void run(String...  args) throws Exception { System.out.println(">>>>This is MyStartupRunnerTest Order=2. Only testing CommandLineRunner... < < < < "); }}Copy the code

3. After Spring Boot is started, check the console output as follows:

>>>>This is MyStartupRunnerTest Order=1. Only testing CommandLineRunner... <<<< >>>>This is MyStartupRunnerTest2 Order=2. Only testing CommandLineRunner... <<<<Copy the code

4.Application startup class code is omitted.

CommandLineRunner interfaces are run in ascending Order based on the values annotated with @ORDER. A smaller value indicates a higher priority.