實際應(yīng)用中,我們會有在項目服務(wù)啟動的時候就去加載一些數(shù)據(jù)或做一些事情這樣的需求。
為了解決這樣的問題,spring Boot 為我們提供了一個方法,通過實現(xiàn)接口 CommandLineRunner 來實現(xiàn)。
創(chuàng)建實現(xiàn)接口 CommandLineRunner 的類,通過@Component注解,就可以實現(xiàn)啟動時加載數(shù)據(jù)項。使用@Order 注解來定義執(zhí)行順序。
IndexStartupRunner.Java類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 服務(wù)啟動執(zhí)行 */ @Component @Order (value= 1 ) public class IndexStartupRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(" IndexStartupRunner >>>>>>>>>>>>>>>服務(wù)啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作 <<<<<<<<<<<<<"); } } IndexStartupRunner2.java類: import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 服務(wù)啟動執(zhí)行 */ @Component @Order (value= 2 ) public class IndexStartupRunner2 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(" IndexStartupRunner2 >>>>>>>>>>>>>>>服務(wù)啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作 <<<<<<<<<<<<<"); } } |
啟動程序后,控制臺輸出結(jié)果為:
>>>>>>>>>>>>>>>IndexStartupRunner服務(wù)啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作<<<<<<<<<<<<<
>>>>>>>>>>>>>>>IndexStartupRunner2服務(wù)啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作<<<<<<<<<<<<<
根據(jù)控制臺結(jié)果可判斷,@Order 注解的執(zhí)行優(yōu)先級是按value值從小到大順序。
ComandLineRunner和ApplicationRunner區(qū)別和使用
如果需要在springapplication啟動之后運行一些特定的代碼,可以實現(xiàn) ApplicationRunner 或
CommandLineRunner 接口。 兩個接口以相同的方式工作,并提供了一??個單一的 run 方法,該方法將被調(diào)用
SpringApplication.run(…?) 完成之前。
這兩個接口的不同之處在于:ApplicationRunner中run方法的參數(shù)為ApplicationArguments,而CommandLineRunner接口中run方法的參數(shù)為String數(shù)組。
以上所述是小編給大家介紹的spring boot啟動加載數(shù)據(jù)原理分析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://www.cnblogs.com/web424/p/6755996.html