1. 程式人生 > >springboot SpringApplication 的十大特性

springboot SpringApplication 的十大特性

sna nco exit failed nconf 橫幅 ica 程序 arguments

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 thats 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.*

@Component
public 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.*

@Component
public 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()被調用後,將與改代碼作為狀態碼返回。

@SpringBootApplication
public 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 的十大特性