CommandLineRunner接口的作用
在平常開發中可能需要實現在啟動后執行的功能,Springboot提供了一種簡單的實現方案,即實現CommandLineRunner
接口,實現功能的代碼在接口的run
方法里。
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指定執行順序。
@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(">>>>>>>>>>>>>>>服務第二順序啟動執行,執行加載數據等操作<<<<<<<<<<<<<");
}
}