Spring Boot命令列執行器
CommandLineRunner是一個帶有run方法的簡單spring引導介面。Spring Boot啟動後將自動呼叫實現CommandLineRunner介面的所有bean的run方法。
Command Line Runner在載入應用程式上下文之後以及Spring Application run方法完成之前執行,相當於你的應用的初始化過程,一般用來實現一些資料預先載入或預先處理。
@SpringBootApplication <b>public</b> <b>class</b> DemoApplication implements CommandLineRunner { <b>private</b> <b>final</b> Logger logger = LoggerFactory.getLogger(DemoApplication.<b>class</b>); <b>public</b> <b>static</b> <b>void</b> main(String args) { SpringApplication.run(DemoApplication.<b>class</b>, args); } @Override <b>public</b> <b>void</b> run(String... strings) throws Exception { .... } }
上面的run方法引數是命令列引數,使用java -jar 啟動這個應用的命令列引數。
如果有多個命令列執行器,可以進行排序:
@Component @Order(1) <b>public</b> <b>class</b> AnotherDatabaseLoader implements CommandLineRunner { @Component @Order(2) <b>public</b> <b>class</b> DataLoader implements CommandLineRunner {
另外一種在主應用的寫法:
@SpringBootApplication <b>public</b> <b>class</b> UnsplashApplication { <b>public</b> <b>static</b> <b>void</b> main(String args) { SpringApplication.run(UnsplashApplication.<b>class</b>, args); } @Bean CommandLineRunner runner(){ <b>return</b> args -> { System.out.println(<font>"CommandLineRunner running in the UnsplashApplication class..."</font><font>); }; } } </font>