有时候我们需要在spring boot容器启动并加载完后,开一些线程或者一些程序来干某些事情。这时候我们需要配置ContextRefreshedEvent事件来实现我们要做的事情
1、ApplicationStartup类
public class ApplicationStartup implements ApplicationListener{ 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容器时触发该事件。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。