有时候我们需要在spring boot容器启动并加载完后,开一些线程或者一些程序来干某些事情。这时候我们需要配置ContextRefreshedEvent事件来实现我们要做的事情
1、ApplicationStartup类
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 类
@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容器时触发该事件。
作者:献给记性不好的自己
链接:http://www.jianshu.com/p/01f7a971a4b9
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。