In practice, we will need to load some data or do something like this when the project service is started.
To solve this problem, Spring Boot provides a way for us to implement the interface Commandlinerunner.
It's simple, you just need one class, no other configuration.
To create a class that implements interface Commandlinerunner
PackageOrg.springboot.sample.runner;ImportOrg.springframework.boot.CommandLineRunner;ImportOrg.springframework.stereotype.Component;/** * Service Start execution * * @author Tan Hongyu (365384722) * @myblog http://blog.csdn.net/catoop/* @create January 9, 2016 * /@Component Public class MyStartupRunner1 implements Commandlinerunner { @Override Public void Run(String ... args)throwsException {System.out.println (The >>>>>>>>>>>>>>> service starts execution, performs loading data, and so on <<<<<<< <<<<<< "); }}
After the Spring boot application starts, it iterates through the instances of the Commandlinerunner interface and runs their run methods. You can also use @order annotations (or implement the Order interface) to specify the order in which all Commandlinerunner instances run.
Below we use @order annotations to define the order of execution.
PackageOrg.springboot.sample.runner;ImportOrg.springframework.boot.CommandLineRunner;ImportOrg.springframework.core.annotation.Order;ImportOrg.springframework.stereotype.Component;/** * Service Start execution * * @author Tan Hongyu (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)throwsException {System.out.println (The >>>>>>>>>>>>>>> service starts execution, performs loading data, and so on 11111111 <<<<< <<<<<<<< "); }}
PackageOrg.springboot.sample.runner;ImportOrg.springframework.boot.CommandLineRunner;ImportOrg.springframework.core.annotation.Order;ImportOrg.springframework.stereotype.Component;/** * Service Start execution * * @author Tan Hongyu (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)throwsException {System.out.println (The >>>>>>>>>>>>>>> service starts execution, performs loading data, and so on 22222222 <<<<< <<<<<<<< "); }}
After you start the program, the console outputs the result:
>>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 22222222 <<<<<<<<<<<<<>>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 11111111 <<<<<<<<<<<<<
Depending on the console results, the execution priority of @Order annotations is from small to large in order of value values.
Spring boot boot Load data commandlinerunner