springboot之啓動加載數據 CommandLineRunner 和ApplicationRunner

Spring Boot 啓動加載數據 CommandLineRunner 和ApplicationRunner
在實際應用中,我們會有在項目服務啓動的時候就去加載一些數據或做一些事情這樣的需求。
爲了解決這樣的問題,springboot爲我們提供了一個方法,通過實現接口 CommandLineRunner 和ApplicationRunner來實現。
Springboot應用程序在啓動後,會遍歷CommandLineRunner接口的實例並運行它們的run方法。也可以利用@Order註解(或者實現Order接口)來規定所有CommandLineRunner實例的運行順序。
根據控制檯結果可判斷,@Order 註解的執行優先級是按value值從小到大順序。

本例將採用maven管理,代碼託管在github上,地址:https://github.com/wolf909867753/springboot

1。創建maven-module,runnerDesc,並在pom.xml中添加springboot依賴

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <artifactId>runnerDesc</artifactId>
    <packaging>war</packaging>
    <name>springboot-runnerDesc (CommandLineRunner and ApplicationRunner)Demo</name>
    <url>http://maven.apache.org</url>

    <!-- Spring Boot 啓動父依賴 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring Boot Web 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>runnerDesc</finalName>
    </build>
</project>

2.工程目錄如下:


@Component
@Order(value = 1)//優先級
public class TestImplApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>服務啓動執行,執行加載數據等操作 11111111 <<<<<<<<<<<<<");
    }
}

@Component
@Order(value = 2)//優先級
public class TestImplCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... strings) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>服務啓動執行,執行加載數據等操作 22222222 <<<<<<<<<<<<<");
    }

    public static void main(String[] args) {
        SpringApplication.run(TestImplCommandLineRunner.class,args);
    }
}


3.編譯代碼並添加到tomcat或者jetty運行
>>>>>>>>>>>>>>>服務啓動執行,執行加載數據等操作 11111111 <<<<<<<<<<<<<
>>>>>>>>>>>>>>>服務啓動執行,執行加載數據等操作 22222222 <<<<<<<<<<<<<

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章