Springboot給我們提供了兩種“開機(jī)啟動(dòng)”某些方法的方式:ApplicationRunner和CommandLineRunner。
這兩種方法提供的目的是為了滿足,在項(xiàng)目啟動(dòng)的時(shí)候立刻執(zhí)行某些方法。我們可以通過實(shí)現(xiàn)ApplicationRunner和CommandLineRunner,來實(shí)現(xiàn),他們都是在SpringApplication 執(zhí)行之后開始執(zhí)行的。
CommandLineRunner接口可以用來接收字符串?dāng)?shù)組的命令行參數(shù),ApplicationRunner 是使用ApplicationArguments 用來接收參數(shù)的,貌似后者更牛逼一些。
先看看CommandLineRunner :
packagecom.springboot.study;importorg.springframework.boot.CommandLineRunner;importorg.springframework.stereotype.Component;/**
* Created by pangkunkun on 2017/9/3.
*/@ComponentpublicclassMyCommandLineRunnerimplementsCommandLineRunner{@Overridepublicvoidrun(String... var1)throwsException{? ? ? ? System.out.println("This will be execute when the project was started!");? ? }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ApplicationRunner :
packagecom.springboot.study;importorg.springframework.boot.ApplicationArguments;importorg.springframework.boot.ApplicationRunner;importorg.springframework.stereotype.Component;/**
* Created by pangkunkun on 2017/9/3.
*/@ComponentpublicclassMyApplicationRunnerimplementsApplicationRunner{@Overridepublicvoidrun(ApplicationArguments var1)throwsException{? ? ? ? System.out.println("MyApplicationRunner class will be execute when the project was started!");? ? }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
這兩種方式的實(shí)現(xiàn)都很簡單,直接實(shí)現(xiàn)了相應(yīng)的接口就可以了。記得在類上加@Component注解。
如果想要指定啟動(dòng)方法執(zhí)行的順序,可以通過實(shí)現(xiàn)org.springframework.core.Ordered接口或者使用org.springframework.core.annotation.Order注解來實(shí)現(xiàn)。
這里我們以ApplicationRunner 為例來分別實(shí)現(xiàn)。
Ordered接口:
packagecom.springboot.study;importorg.springframework.boot.ApplicationArguments;importorg.springframework.boot.ApplicationRunner;importorg.springframework.core.Ordered;importorg.springframework.stereotype.Component;/**
* Created by pangkunkun on 2017/9/3.
*/@ComponentpublicclassMyApplicationRunnerimplementsApplicationRunner,Ordered{@OverridepublicintgetOrder(){return1;//通過設(shè)置這里的數(shù)字來知道指定順序}@Overridepublicvoidrun(ApplicationArguments var1)throwsException{? ? ? ? System.out.println("MyApplicationRunner1!");? ? }}
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
Order注解實(shí)現(xiàn)方式:
packagecom.springboot.study;importorg.springframework.boot.ApplicationArguments;importorg.springframework.boot.ApplicationRunner;importorg.springframework.core.Ordered;importorg.springframework.core.annotation.Order;importorg.springframework.stereotype.Component;/**
* Created by pangkunkun on 2017/9/3.
* 這里通過設(shè)定value的值來指定執(zhí)行順序
*/@Component@Order(value =1)publicclassMyApplicationRunnerimplementsApplicationRunner{@Overridepublicvoidrun(ApplicationArguments var1)throwsException{? ? ? ? System.out.println("MyApplicationRunner1!");? ? }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
這里不列出其他對比方法了,自己執(zhí)行下就好。