Spring Boot starts to load data CommandLineRunner
In practical applications, we need to load some data or do some things when the project service starts.
To solve this problem, Spring Boot provides us with a method to implement it through the implementation interface CommandLineRunner.
It is very simple. You only need one class and no other configurations are required.
Create a CommandLineRunner class
Package org. springboot. sample. runner; import org. springframework. boot. commandLineRunner; import org. springframework. stereotype. component;/*** Service Startup execution ** @ author single Hongyu (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create January 9, 2016 */@ Componentpublic class MyStartupRunner1 implements CommandLineRunner {@ Override public void run (String... args) throws Exception {System. out. println (">>>>>>>>>>>>>>>> Service Startup execution, perform data loading and other operations <");}}
After the Spring Boot application is started, it traverses the instances of the CommandLineRunner interface and runs their run method. You can also use the @ Order annotation (or implement the Order Interface) to specify the running sequence of all CommandLineRunner instances.
As follows, we use the @ Order annotation to define the execution sequence.
Package org. springboot. sample. runner; import org. springframework. boot. commandLineRunner; import org. springframework. core. annotation. order; import org. springframework. stereotype. component;/*** Service Startup execution ** @ author single redwoo (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create January 9, 2016 */@ Component @ Order (value = 2) public class MyStartupRunner1 implements CommandLineRunner {@ Override public void run (String... args) throws Exception {System. out. println (">>>>>>>>>>>>>>>> Service Startup execution, perform data loading and other operations 11111111 <");}}
Package org. springboot. sample. runner; import org. springframework. boot. commandLineRunner; import org. springframework. core. annotation. order; import org. springframework. stereotype. component;/*** Service Startup execution ** @ author single redwoo (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create January 9, 2016 */@ Component @ Order (value = 1) public class MyStartupRunner2 implements CommandLineRunner {@ Override public void run (String... args) throws Exception {System. out. println (">>>>>>>>>>>>>>>> Service Startup execution, perform data loading and other operations 22222222 <");}}
After the program is started, the console outputs the following results:
>>>>>>>>>>>>>> Service Startup execution, perform operations such as data loading: <>>>>>>>>>>> start and run the service, perform data loading and other operations 11111111 <
According to the console results, the execution priority of the @ Order annotation is in ascending Order of value values.