在日常開發中可能須要實如今啓動後執行的功能,Springboot提供了一種簡單的實現方案,即實現CommandLineRunner
接口,實現功能的代碼在接口的run
方法裏。java
import org.springframework.core.annotation.Order; public interface CommandLineRunner { /** * Callback used to run the bean. * @param args incoming main method arguments * @throws Exception on error */ void run(String... args) throws Exception; }
package com.lucky.spring; import com.alibaba.druid.pool.DruidDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; @SpringBootApplication public class Application implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>>>服務啓動執行"); } }
當服務中有多個CommandLineRunner對象時,默認狀況下是按照天然順序執行的。能夠經過@Order指定執行順序。spring
@Component @Order(value = 1) public class StartRunnerOne implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>服務啓動第一個開始執行的任務,執行加載數據等操做<<<<<<<<<<<<<"); } } @Component @Order(value = 2) public class StartupRunnerTwo implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>服務第二順序啓動執行,執行加載數據等操做<<<<<<<<<<<<<"); } }