commandlinerunner是一個帶有run方法的簡單spring引導接口。spring boot啟動后將自動調用實現commandlinerunner接口的所有bean的run方法。
command line runner在加載應用程序上下文之后以及spring application run方法完成之前執行,相當于你的應用的初始化過程,一般用來實現一些數據預先加載或預先處理。
1
2
3
4
5
6
7
8
9
10
11
|
@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 啟動這個應用的命令行參數。
如果有多個命令行運行器,可以進行排序:
1
2
3
4
5
6
7
|
@component @order ( 1 ) <b> public </b> <b> class </b> anotherdatabaseloader implements commandlinerunner { @component @order ( 2 ) <b> public </b> <b> class </b> dataloader implements commandlinerunner { |
另外一種在主應用的寫法:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@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> |
總結
以上所述是小編給大家介紹的spring boot命令行運行器的實現方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.jdon.com/50511