有时候我们需要在spring boot容器启动并加载完后,开一些线程或者一些程序来干某些事情。这时候我们需要配置ContextRefreshedEvent事件来实现我们要做的事情
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层来操作数据库 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容器初始化或者刷新时触发该事件。
2、 ContextStartedEvent:当使用ConfigurableApplicationContext接口的start()方法启动ApplicationContext容器时触发该事件。
3、 ContextClosedEvent:当使用ConfigurableApplicationContext接口的close()方法关闭ApplicationContext容器时触发该事件。
4、 ContextStopedEvent: 当使用ConfigurableApplicationContext接口的stop()方法停止ApplicationContext容器时触发该事件。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.jianshu.com/p/01f7a971a4b9