springboot SpringApplication 的十大特性

來源:互聯網
上載者:User

標籤:log   setw   new   XML   debug   gem   initial   lin   err   

1、啟動失敗

如果你啟動項目失敗,你通過註冊FailureAnalyzers 來擷取錯誤資訊和解決辦法。比如你啟動應用的8080連接埠被佔用了,你將看到如下資訊:

***************************APPLICATION FAILED TO START***************************Description:Embedded servlet container failed to start. Port 8080 was already in use.Action:Identify and stop the process that‘s listening on port 8080 or configure this application to listen on another port.

Spring Boot提供了大量的FailureAnalyzer 實作類別,同時你也可以實現一個自己的。

你還可以通過開啟debug屬性或者在log日誌配置org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer來讓Exception更加容易理解。

開啟debug屬性可以啟動命令後面加 --debug

$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug

2、定製橫幅

啟動時候的橫幅可以通過在classpath下面添加一個banner.txt,當然你也可以通過屬性檔案的banner.location指定檔案和banner.charset指定檔案編碼(預設UTF-8)。也可以通過在classpath下添加banner.png、banner.gif、banner.jpg來替換橫幅為圖片,或者設定屬性banner.image.location指定圖片,圖片將會轉換文本形式顯示出來。

 橫幅內部可以通過EL運算式使用以下屬性:

${application.version}   MANIFEST.MF檔案中的版本號碼,如Implementation-Version: 1.0將會列印成1.0

${application.formatted-version} 也是列印版本號碼,不過版本號碼前面會加個v

${spring-boot.version} springboot版本

${spring-boot.formatted-version} 也是springboot版本,前面加個v

${application.title} MANIFEST.MF定義的應用程式名稱,如Implementation-Title: MyApp將會列印MyApp

也可以通過SpringApplication.setBanner(…?)方式來設定橫幅,實現org.springframework.boot.Banner介面的printBanner()方法來產生你的橫幅。

可以通過設定spring.main.banner-mode屬性來設定橫幅展示與否(log,off)。

3、定製SpringApplication

如果官方內建的SpringApplication 不合你的口味,你可以自訂一個,比如,關閉Banner你可以這樣寫:

public static void main(String[] args) {    SpringApplication app = new SpringApplication(MySpringConfiguration.class);    app.setBannerMode(Banner.Mode.OFF);    app.run(args);}

建構函式傳給SpringApplication 的參數是SpringBeans的項目配置,多數情況下可以參考@Configuration類或者被掃描的xml。

同時,也可以通過屬性檔案來配置這些,後面會做介紹。

 4、Fluent Builder API

你如果需要建立一個多層ApplicationContext(多個父子關係的Context),可以使用Fluent Builder API, 用類SpringApplicationBuilder實現。例如:

new SpringApplicationBuilder()        .sources(Parent.class)        .child(Application.class)        .bannerMode(Banner.Mode.OFF)        .run(args);

更多請瞭解SpringApplicationBuilder的API文檔:https://docs.spring.io/spring-boot/docs/1.5.7.RELEASE/api/org/springframework/boot/builder/SpringApplicationBuilder.html

5、應用事件與監聽器

除了SpringFramework常用的事件ContextRefreshedEvent外,SpringApplication也添加了很多事件。

很多事件在SpringApplication建立之前就被觸發了,所以你不能以Bean的形式對這些事件註冊監聽器。

你可以通過SpringApplication.addListeners(…?)或SpringApplicationBuilder.listeners(…?)方法來註冊他們。

如果你想讓你的監聽器能自動建立且不受SpringApplication的建立影響,你可以在項目中添加META-INF/spring.factories檔案並設定org.springframework.context.ApplicationListener的值為監聽器的類,如下:

org.springframework.context.ApplicationListener=com.example.project.MyListener

以下為常見事件:

ApplicationStartingEvent在應用啟動之後、listeners 和initializers註冊之前觸發。

ApplicationEnvironmentPreparedEvent在Context啟動前準備使用Environment之前觸發。

ApplicationPreparedEvent在重新整理後、定義的Bean被載入前。

ApplicationReadyEvent在重新整理後所有的回呼函數執行已經執行完、應用已經準備好相應請求。

ApplicationFailedEvent在啟動時應用拋出異常觸發。

 6、Web環境變數

SpringApplication會試圖建立一個正確的ApplicationContext來維護你的利益。預設情況下,會根據你是否在開發環境下啟動來啟動AnnotationConfigApplicationContext還是AnnotationConfigEmbeddedWebApplicationContext。

判斷環境變數的方法是相當簡單的(通過少數類來判斷),你可以通過setWebEnvironment(boolean webEnvironment)來直接設定。

7、參數

如果你要給SpringApplication.run(…?)傳入參數,你可以注入org.springframework.boot.ApplicationArguments對象,ApplicationArguments提供了訪問String[]參數的入口,如下:

import org.springframework.boot.*import org.springframework.beans.factory.annotation.*import org.springframework.stereotype.*@Componentpublic class MyBean {    @Autowired    public MyBean(ApplicationArguments args) {        boolean debug = args.containsOption("debug");        List<String> files = args.getNonOptionArgs();        // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"]    }}

你也可以註冊CommandLinePropertySource,通過@Value註解來注入參數。

8、ApplicationRunner 或 CommandLineRunner

如果你需要在SpringApplication啟動後執行一些代碼,你可以實現ApplicationRunner 或 CommandLineRunner。這兩個方法會在SpringApplication的run方法執行完後執行run方法。

import org.springframework.boot.*import org.springframework.stereotype.*@Componentpublic class MyBean implements CommandLineRunner {    public void run(String... args) {        // Do something...    }}

你可以通過實現org.springframework.core.Ordered介面或使用org.springframework.core.annotation.Order註解來在特定代碼中調用對應的ApplicationRunner 或 CommandLineRunner的bean。

 9、SpringApplication 應用退出

每一個SpringApplication都會在JVM註冊一個程式關閉的鉤子來保證應用優雅關閉。所有的Spring標準生命週期函數(如DisposableBean介面、或@PreDestroy)都會被執行。

你可以通過實現org.springframework.boot.ExitCodeGenerator介面。介面將會返回 特定的狀態代碼,當SpringApplication.exit()被調用後,將與改代碼作為狀態代碼返回。

@SpringBootApplicationpublic class ExitCodeApplication {    @Bean    public ExitCodeGenerator exitCodeGenerator() {        return new ExitCodeGenerator() {            @Override            public int getExitCode() {                return 42;            }        };    }    public static void main(String[] args) {        System.exit(SpringApplication                .exit(SpringApplication.run(ExitCodeApplication.class, args)));    }}

而ExitCodeGenerator介面為退出異常調用的介面。

10、Admin

通過屬性 spring.application.admin.enabled 可以開啟SpringApplication的admin-related特徵,這將會在MBeanServer平台暴露SpringApplicationAdminMXBean介面。你可以通過此對SpringApplication進行遠端管理。

如果你想知道它在哪個連接埠運行,可以查詢屬性local.server.port的值。

 

springboot SpringApplication 的十大特性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.