配置SpringApplication
如果SpringApplication無法滿足要求,你可以自己創建一個局部實例,然后對其進行設置:
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MySpringConfiguration.class);
//關閉Banner打印
app.setBannerMode(Banner.Mode.OFF);
//添加監聽器
app.addListeners(new MyListener());
... app.run(args); }
- 1
SpringApplication的相關配置將會被@Configuration注解的類,XML配置文件,以及Spring掃描的包引用。更詳細的配置選項,參見SpringApplication Javadoc。
你也可以通過SpringApplicationBuilder來對SpringApplication的屬性進行配置,這樣的結構更有層次感。SpringApplicationBuilder為構建 SpringApplication 和 ApplicationContext 實例提供了一套便利的流式API:
new SpringApplicationBuilder()
.sources(Parent.class)
.child(Application.class)
.bannerMode(Banner.Mode.OFF)
.listeners(new MyListener())
... .run(args);
SpringApplication將會根據需要創建一個ApplicationContext,默認情況下,如果是非web應用,則會創建一個AnnotationConfigApplicationContext上下文,如果是web應用,則會創建一個AnnotationConfigEmbeddedWebApplicationContext上下文。當然,你也可以通過setWebEnvironment(boolean webEnvironment)來覆蓋默認的設置。
ApplicationRunner 和 CommandLineRunner
如果你希望在SpringApplication啟動之前完成某些操作,你可以通過實現ApplicationRunner或者CommandLineRunner接口來實現。這兩個接口提供了一個run方法,會在SpringApplication.run(…)完成之前被調用。適用於系統初始化配置的加載,啟動檢查等等。
import org.springframework.boot.* import org.springframework.stereotype.* @Component public class MyBean implements CommandLineRunner { public void run(String... args) { // Do something... } }
如果有多個CommandLineRunner或者ApplicationRunner的實現,並且這些都需要按照一定的順序來執行,你可以通過實現org.springframework.core.Ordered接口或者使用org.springframework.core.annotation.Order注解來設置這些的執行順序。
配置Banner
你可以通過添加一個banner.txt文件到你的classpath路徑下,來改變在啟動的時候打印的banner信息,或者通過設置banner.location屬性來設置該文件的位置,通過banner.charset來設置文件的編碼,你也可以添加banner.gif,banner.jpg, `banner.png圖片文件到classpath,或者通過設置banner.image.location屬性來作為banner信息,這些圖片會被轉換為有藝術感的ASCII,並且打印在文本的頂部。banner.txt中可以設置如下的占位符:
| 變量 | 描述 |
|---|---|
${application.version} |
The version number of your application as declared in MANIFEST.MF. For example Implementation-Version: 1.0 is printed as 1.0. |
${application.formatted-version} |
The version number of your application as declared in MANIFEST.MF formatted for display (surrounded with brackets and prefixed with v). For example (v1.0). |
${spring-boot.version} |
The Spring Boot version that you are using. For example 1.4.1.RELEASE. |
${spring-boot.formatted-version} |
The Spring Boot version that you are using formatted for display (surrounded with brackets and prefixed with v). For example (v1.4.1.RELEASE). |
${Ansi.NAME} (or ${AnsiColor.NAME}, ${AnsiBackground.NAME}, ${AnsiStyle.NAME}) |
Where NAME is the name of an ANSI escape code. See AnsiPropertySource for details. |
${application.title} |
The title of your application as declared in MANIFEST.MF. For example Implementation-Title: MyApp is printed as MyApp. |
可以通過設置spring.main.banner-mode屬性來控制輸出,如下,在application.properties文件中添加如下屬性,將會覆蓋SpringApplication中的默認配置:
# 打印到控制台 spring.main.banner-mode=console # 打印到日志文件 # spring.main.banner-mode=log # 不打印 # spring.main.banner-mode=off
