標籤:多個 產生 figure 順序 資訊 獲得 exce lamda autoconf
首先看實現了兩個介面啟動並執行順序結果:
My1:
package com.example.commandlinerunner;
import lombok.extern.java.Log;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.annotation.OrderUtils;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* Created by WangYx on 2017/9/14.
*/
@Component
@Order(6)
@Log
public class MyCmdLinerRunner1 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("MyCmdLinerRunner1:order = " + OrderUtils.getOrder(this.getClass())+" :args = "
+ Arrays.toString(args));
}
private String getStacks(){
StringBuilder sb = new StringBuilder();
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
sb.append("=============\n");
for (int i = 0 ; i < elements.length ; i++){
sb.append(elements[i]).append("\n");
}
return sb.toString();
}
}
My2:
package com.example.commandlinerunner;
import lombok.extern.java.Log;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.annotation.OrderUtils;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* Created by WangYx on 2017/9/14.
*/
@Component
@Order(5)
@Log
public class MyCmdLinerRunner2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("MyCmdLinerRunner2:order = " + OrderUtils.getOrder(this.getClass())+" :args = "
+ Arrays.toString(args));
}
}
主函數:
package com.example.commandlinerunner;
/**
* 通過CommandLineRunner,可在所有Spring Bean和 ApplicationContext被建立後執行一些可以訪問命令列參數的任務。
* 如想指定多個CommandLineRunnerBean的執行順序,
* 可以實現org.springframework.core.Ordered介面
* 或添加org.springframework.core.annotation.Order註解
*/
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CommandlinerunnerApplication {
public static void main(String[] args) {
SpringApplication.run(CommandlinerunnerApplication.class, args);
}
}
/**
* org.springframework.core.annotation.AnnotationAwareOrderComparator負責對CommandLineRunnerBean進行排序。定序為:
如果有一方是org.springframework.core.PriorityOrdered介面實現,而另一方不是,則PriorityOrdered介面實現一方獲勝;
檢查org.springframework.core.Ordered介面或 org.springframework.core.annotation.Order 註解獲得order,值小者勝;
其他沒有order的則置為Ordered.LOWEST_PRECEDENCE,順序不定。
在上述測試中,MyCmdLineRunner2的order為5,MyCmdLineRunner1的order為6,因此MyCmdLineRunner2在MyCmdLineRunner1之前執行。
Application的demo1和demo2方法設定了@order註解,但是調試可知lamda運算式產生類並沒有@order註解資訊,因此執行順序排在後面。
這是需要注意的地方。此外,Bean初始化順序跟CommandLineRunner執行順序也沒有關係。
*/
springboot 中的commandLineRunners介面