springboot給我們提供了兩種“開機啟動”某些方法的方式:applicationrunner和commandlinerunner。
這兩種方法提供的目的是為了滿足,在項目啟動的時候立刻執(zhí)行某些方法。我們可以通過實現(xiàn)applicationrunner和commandlinerunner,來實現(xiàn),他們都是在springapplication 執(zhí)行之后開始執(zhí)行的。
commandlinerunner接口可以用來接收字符串數(shù)組的命令行參數(shù),applicationrunner 是使用applicationarguments 用來接收參數(shù)的,貌似后者更牛逼一些。
先看看commandlinerunner :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package com.springboot.study; import org.springframework.boot.commandlinerunner; import org.springframework.stereotype.component; /** * created by pangkunkun on 2017/9/3. */ @component public class mycommandlinerunner implements commandlinerunner{ @override public void run(string... var1) throws exception{ system.out.println( "this will be execute when the project was started!" ); } } |
applicationrunner :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package com.springboot.study; import org.springframework.boot.applicationarguments; import org.springframework.boot.applicationrunner; import org.springframework.stereotype.component; /** * created by pangkunkun on 2017/9/3. */ @component public class myapplicationrunner implements applicationrunner { @override public void run(applicationarguments var1) throws exception{ system.out.println( "myapplicationrunner class will be execute when the project was started!" ); } } |
這兩種方式的實現(xiàn)都很簡單,直接實現(xiàn)了相應的接口就可以了。記得在類上加@component注解。
如果想要指定啟動方法執(zhí)行的順序,可以通過實現(xiàn)org.springframework.core.ordered接口或者使用org.springframework.core.annotation.order注解來實現(xiàn)。
這里我們以applicationrunner 為例來分別實現(xiàn)。
ordered接口:
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
|
package com.springboot.study; import org.springframework.boot.applicationarguments; import org.springframework.boot.applicationrunner; import org.springframework.core.ordered; import org.springframework.stereotype.component; /** * created by pangkunkun on 2017/9/3. */ @component public class myapplicationrunner implements applicationrunner,ordered{ @override public int getorder(){ return 1 ; //通過設置這里的數(shù)字來知道指定順序 } @override public void run(applicationarguments var1) throws exception{ system.out.println( "myapplicationrunner1!" ); } } |
order注解實現(xiàn)方式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package com.springboot.study; import org.springframework.boot.applicationarguments; import org.springframework.boot.applicationrunner; import org.springframework.core.ordered; import org.springframework.core.annotation.order; import org.springframework.stereotype.component; /** * created by pangkunkun on 2017/9/3. * 這里通過設定value的值來指定執(zhí)行順序 */ @component @order (value = 1 ) public class myapplicationrunner implements applicationrunner{ @override public void run(applicationarguments var1) throws exception{ system.out.println( "myapplicationrunner1!" ); } } |
這里不列出其他對比方法了,自己執(zhí)行下就好。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_35981283/article/details/77826537