1. 程式人生 > >spring boot容器加載完後執行特定操作

spring boot容器加載完後執行特定操作

文件中 code buck 線程 private tor tope gets send

有時候我們需要在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
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請註明出處。

spring boot容器加載完後執行特定操作