有時候我們需要在spring boot容器啟動并加載完后,開一些線程或者一些程序來干某些事情。這時候我們需要配置ContextRefreshedEvent事件來實現(xiàn)我們要做的事情
1、ApplicationStartup類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent>{ public void onApplicationEvent(ContextRefreshedEvent event) { //在容器加載完畢后獲取dao層來操作數(shù)據(jù)庫 OSSVideoRepository ossVideoRepository = (OSSVideoRepository)event.getApplicationContext().getBean(OSSVideoRepository. class ); //在容器加載完畢后獲取配置文件中的配置 ServerConfig serverConfig = (ServerConfig)event.getApplicationContext().getBean(ServerConfig. class ); ServerFileScanner fileScanner = new ServerFileScanner( ossVideoRepository, serverConfig.getScanpath()); //在容器加載完畢后啟動線程 Thread thread = new Thread(fileScanner); thread.start(); } } |
2、ServerConfig 類
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
@Component @ConfigurationProperties (prefix = "server" ) public class ServerConfig { private String aliyunossEndpoint; private String aliyunossAccessKeyId; private String aliyunossAccessKeySecret; private String aliyunossBucketName; private String scanpath; public String getAliyunossEndpoint() { return aliyunossEndpoint; } public void setAliyunossEndpoint(String aliyunossEndpoint) { this .aliyunossEndpoint = aliyunossEndpoint; } public String getAliyunossAccessKeyId() { return aliyunossAccessKeyId; } public void setAliyunossAccessKeyId(String aliyunossAccessKeyId) { this .aliyunossAccessKeyId = aliyunossAccessKeyId; } public String getAliyunossAccessKeySecret() { return aliyunossAccessKeySecret; } public void setAliyunossAccessKeySecret(String aliyunossAccessKeySecret) { this .aliyunossAccessKeySecret = aliyunossAccessKeySecret; } public String getAliyunossBucketName() { return aliyunossBucketName; } public void setAliyunossBucketName(String aliyunossBucketName) { this .aliyunossBucketName = aliyunossBucketName; } public String getScanpath() { return scanpath; } public void setScanpath(String scanpath) { this .scanpath = scanpath; } } |
PS:還有一些spring內置的事件
1、 ContextRefreshedEvent:ApplicationContext容器初始化或者刷新時觸發(fā)該事件。
2、 ContextStartedEvent:當使用ConfigurableApplicationContext接口的start()方法啟動ApplicationContext容器時觸發(fā)該事件。
3、 ContextClosedEvent:當使用ConfigurableApplicationContext接口的close()方法關閉ApplicationContext容器時觸發(fā)該事件。
4、 ContextStopedEvent: 當使用ConfigurableApplicationContext接口的stop()方法停止ApplicationContext容器時觸發(fā)該事件。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.jianshu.com/p/01f7a971a4b9