Spring Boot特性

摘要: 1. SpringApplication SpringApplication 類是啟動 Spring Boot 應用的入口類,你可以創建一個包含 main() 方法的類,來運行 SpringApplication.run 這個靜態方法: public static void main(String...

1. SpringApplication

SpringApplication 類是啟動 Spring Boot 應用的入口類,你可以創建一個包含 main() 方法的類,來運行 SpringApplication.run 這個靜態方法:

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

運行該類會有如下輸出:

 . ____ _ __ _ _
/\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\
( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\
\\\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: v1.2.2.RELEASE

1.1 自定義Banner

通過在classpath下添加一個banner.txt或設置banner.location來指定相應的文件可以改變啟動過程中打印的banner。如果這個文件有特殊的編碼,你可以使用banner.encoding設置它(默認為UTF-8)。

在banner.txt中可以使用如下的變量:

  • ${application.version}:MANIFEST.MF 文件中的應用版本號
  • ${application.formatted-version}
  • ${spring-boot.version}:你正在使用的 Spring Boot 版本號
  • ${spring-boot.formatted-version}

上面這些變量也可以通過 application.properties 來設置,後面再作介紹。

注:如果想以編程的方式產生一個banner,可以使用SpringBootApplication.setBanner(…)方法。使用org.springframework.boot.Banner接口,實現你自己的printBanner()方法。

1.2 自定義SpringApplication

如果默認的SpringApplication不符合你的口味,你可以創建一個本地的實例並自定義它。例如,關閉banner你可以這樣寫:

public static void main(String[] args) {
SpringApplication app = new SpringApplication(MySpringConfiguration.class);
app.setShowBanner(false);
app.run(args);
}

1.3 流暢的構建API

如果你需要創建一個分層的ApplicationContext(多個具有父子關係的上下文),或你只是喜歡使用流暢的構建API,你可以使用SpringApplicationBuilder。SpringApplicationBuilder允許你以鏈式方式調用多個方法,包括可以創建層次結構的parent和child方法。

new SpringApplicationBuilder()
.showBanner(false)
.sources(Parent.class)
.child(Application.class)
.run(args);

1.4 Application事件和監聽器

SpringApplication 啟動過程會觸發一些事件,你可以針對這些事件通過 SpringApplication.addListeners(…​) 添加一些監聽器:

  • ApplicationStartedEvent
  • ApplicationEnvironmentPreparedEvent
  • ApplicationPreparedEvent
  • ApplicationFailedEvent

SpringApplication 會註冊一個 shutdown hook 以便在應用退出的時候能夠保證 ApplicationContext 優雅地關閉,這樣能夠保證所有 Spring lifecycle 的回調都會被執行,包括 DisposableBean 接口的實現類以及 @PreDestroy 註解。

另外,你也可以實現 org.springframework.boot.ExitCodeGenerator 接口來定義你自己的退出時候的邏輯。

1.5 Web環境

一個SpringApplication將嘗試為你創建正確類型的ApplicationContext。在默認情況下,使用AnnotationConfigApplicationContext或AnnotationConfigEmbeddedWebApplicationContext取決於你正在開發的是否是web應用。

用於確定一個web環境的算法相當簡單(基於是否存在某些類)。如果需要覆蓋默認行為,你可以使用setWebEnvironment(boolean webEnvironment)。通過調用setApplicationContextClass(…),你可以完全控制ApplicationContext的類型。

注:當JUnit測試裡使用SpringApplication時,調用setWebEnvironment(false)是可取的。

1.6 獲取應用參數

如果你想獲取應用程序傳遞給SpringApplication.run(…​)的參數,你可以注入一個org.springframework.boot.ApplicationArgumentsbean,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"]
}
}
/<string>

Spring Boot也會在Environment中注入一個CommandLinePropertySource,這允許你使用@Value註解注入一個應用參數。

1.7 使用ApplicationRunner或者CommandLineRunner

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

如果一些CommandLineRunner或者ApplicationRunner beans被定義必須以特定的次序調用,你可以額外實現org.springframework.core.Ordered接口或使用@Order註解。

1.8 程序退出

SpringApplication會在JVM上註冊一個關閉的hook已確認ApplicationContext是否優雅的關閉。所有的標準的Spring生命週期回調(例如,DisposableBean接口,或者@PreDestroy註解)都可以使用。

另外,beans可以實現org.springframework.boot.ExitCodeGenerator接口在應用程序結束的時候返回一個錯誤碼。

1.9 管理員特性

通過spring.application.admin.enabled開啟。

2. 外化配置

Spring Boot允許你針對不同的環境配置不同的配置參數,你可以使用 properties文件、YAML 文件、環境變量或者命令行參數來修改應用的配置。你可以在代碼中使用@Value註解來獲取配置參數的值。

Spring Boot使用一個特別的PropertySource來按順序加載配置,加載順序如下:

  • 命令行參數
  • 來自SPRING_APPLICATION_JSON的屬性
  • java:comp/env 中的 JNDI 屬性
  • Java系統環境變量
  • 操作系統環境變量
  • RandomValuePropertySource,隨機值,使用 random.* 來定義
  • jar 包外的 Profile 配置文件,如 application-{profile}.properties 和 YAML 文件
  • jar 包內的 Profile 配置文件,如 application-{profile}.properties 和 YAML 文件
  • jar 包外的 Application 配置,如 application.properties 和 application.yml 文件
  • jar 包內的 Application 配置,如 application.properties 和 application.yml 文件
  • 在標有 @Configuration 註解的類標有@PropertySource註解的
  • 默認值,使用 SpringApplication.setDefaultProperties 設置的

示例代碼:

import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.*
@Component
public class MyBean {
@Value("${name}")
private String name;
// ...
}

你可以在 application.properties 中定義一個 name 變量,或者在運行該 jar 時候,指定一個命令行參數(以 -- 標識),例如:java -jar app.jar --name="Spring"

也可以使用SPRING_APPLICATION_JSON屬性:

$ SPRING_APPLICATION_JSON='{"foo":{"bar":"spam"}}'  

$ java -jar myapp.jar

在這個例子中,你可以在Spring的Environment中通過foo.bar來引用變量。你可以在系統變量中定義pring.application.json:

$ java -Dspring.application.json='{"foo":"bar"}' -jar myapp.jar

或者使用命令行參數:

$ java -jar myapp.jar --spring.application.json='{"foo":"bar"}'

或者使用JNDI變量:

java:comp/env/spring.application.json

2.1 隨機變量

RandomValuePropertySource 類型變量的示例如下:

my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}

2.3 應用屬性文件

SpringApplication 會在以下路徑查找 application.properties 並加載該文件:

  • /config 目錄下
  • 當前目錄
  • classpath 中 /config 包下
  • classpath 根路徑下

另外,你也可以通過 spring.config.location 來指定 application.properties 文件的存放路徑,或者通過 spring.config.name 指定該文件的名稱,例如:

$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

或者:

$ java -jar myproject.jar --spring.config.name=myproject

2.4 指定Profile配置文件

即application-{profile}.properties配置文件。

2.5 佔位符

在application.properties文件中可以引用Environment中已經存在的變量。

app.name=MyApp
app.description=${app.name} is a Spring Boot application

3. Profiles

你可以使用 @Profile 註解來標註應用使用的環境

@Configuration
@Profile("production")
public class ProductionConfiguration {

// ...
}

可以使用 spring.profiles.active 變量來定義應用激活的 profile:

spring.profiles.active=dev,hsqldb

還可以通過 SpringApplication 來設置,調用 SpringApplication.setAdditionalProfiles(…​) 代碼即可。

4. 日誌

Spring Boot 使用 Commons Logging 作為內部記錄日誌,你也可以使用 Java Util Logging, Log4J, Log4J2 和 Logback 來記錄日誌。

默認情況下,如果你使用了 Starter POMs ,則會使用 Logback 來記錄日誌。

默認情況,是輸出 INFO 類型的日誌,你可以通過設置命令行參數--debug來設置:

$ java -jar myapp.jar --debug

如果你的終端支持 ANSI ,則日誌支持彩色輸出,這個可以通過 spring.output.ansi.enabled 設置,可配置的值有:ALWAYS、DETECT、NEVER。

%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}

可選的顏色有:

  • blue
  • cyan
  • faint
  • green
  • magenta
  • red
  • yellow

可以通過 logging.file 和 logging.path 設置日誌輸出文件名稱和路徑。

日誌級別使用 logging.level.*=LEVEL 來定義,例如:

logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR

Spring Boot 通過 logging.config 來定義日誌的配置文件存放路徑,對於不同的日誌系統,配置文件的名稱不同:

LoggingSystem CustomizationLogbacklogback-spring.xml、logback-spring.groovy、logback.xml 、 logback.groovyLog4jlog4j-spring.properties、log4j-spring.xml、log4j.properties 、log4j.xmlLog4j2log4j2-spring.xml、log4j2.xmlJDK (Java Util Logging)logging.properties

對於logback-spring.xml這類的配置,建議使用-spring變量來加載配置文件。

Environment中可以自定義一些屬性:

Spring EnvironmentSystem PropertyCommentslogging.exception-conversion-wordLOG_EXCEPTION_CONVERSION_WORD logging.fileLOG_FILE logging.pathLOG_PATH logging.pattern.consoleCONSOLE_LOG_PATTERN logging.pattern.fileFILE_LOG_PATTERN logging.pattern.levelLOG_LEVEL_PATTERN PIDPID

5. 開發Web應用

5.1 Spring Web MVC框架

一個標準的@RestController例子返回JSON數據:

@RestController
@RequestMapping(value="/users")
public class MyRestController {
@RequestMapping(value="/{user}", method=RequestMethod.GET)
public User getUser(@PathVariable Long user) {
// ...
}
@RequestMapping(value="/{user}/customers", method=RequestMethod.GET)
List<customer> getUserCustomers(@PathVariable Long user) {
// ...
}
@RequestMapping(value="/{user}", method=RequestMethod.DELETE)
public User deleteUser(@PathVariable Long user) {
// ...
}
}
/<customer>

5.1.1 Spring MVC自動配置

Spring Boot為Spring MVC提供適用於多數應用的自動配置功能。在Spring默認基礎上,自動配置添加了以下特性:

  • 引入ContentNegotiatingViewResolver和BeanNameViewResolver beans。
  • 對靜態資源的支持,包括對WebJars的支持。
  • 自動註冊Converter,GenericConverter,Formatter beans。
  • 對HttpMessageConverters的支持。
  • 自動註冊MessageCodeResolver。
  • 對靜態index.html的支持。
  • 對自定義Favicon的支持。
  • 字段使用 ConfigurableWebBindingInitializer bean

如果想全面控制Spring MVC,你可以添加自己的@Configuration,並使用@EnableWebMvc對其註解。如果想保留Spring Boot MVC的特性,並只是添加其他的MVC配置(攔截器,formatters,視圖控制器等),你可以添加自己的WebMvcConfigurerAdapter類型的@Bean(不使用@EnableWebMvc註解)。

5.1.2 HttpMessageConverters

Spring MVC使用HttpMessageConverter接口轉換HTTP請求和響應。合理的缺省值被包含的恰到好處(out of the box),例如對象可以自動轉換為JSON(使用Jackson庫)或XML(如果Jackson XML擴展可用則使用它,否則使用JAXB)。字符串默認使用UTF-8編碼。

如果需要添加或自定義轉換器,你可以使用Spring Boot的HttpMessageConverters類:

import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;
@Configuration
public class MyConfiguration {
@Bean
public HttpMessageConverters customConverters() {
HttpMessageConverter> additional = ...
HttpMessageConverter> another = ...
return new HttpMessageConverters(additional, another);
}
}

任何在上下文中出現的HttpMessageConverter bean將會添加到converters列表,你可以通過這種方式覆蓋默認的轉換器(converters)。

5.1.3 MessageCodesResolver

Spring MVC有一個策略,用於從綁定的errors產生用來渲染錯誤信息的錯誤碼:MessageCodesResolver。如果設置spring.mvc.message-codes-resolver.format屬性為PREFIX_ERROR_CODE或POSTFIX_ERROR_CODE(具體查看DefaultMessageCodesResolver.Format枚舉值),Spring Boot會為你創建一個MessageCodesResolver。

5.1.4 靜態內容

默認情況下,Spring Boot從classpath下一個叫/static(/public,/resources或/META-INF/resources)的文件夾或從ServletContext根目錄提供靜態內容。這使用了Spring MVC的ResourceHttpRequestHandler,所以你可以通過添加自己的WebMvcConfigurerAdapter並覆寫addResourceHandlers方法來改變這個行為(加載靜態文件)。

@Configuration
class ClientResourcesConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("/WEB-INF/resources/")
.setCachePeriod(0);
}
}

在一個單獨的web應用中,容器默認的servlet是開啟的,如果Spring決定不處理某些請求,默認的servlet作為一個回退(降級)將從ServletContext根目錄加載內容。大多數時候,這不會發生(除非你修改默認的MVC配置),因為Spring總能夠通過DispatcherServlet處理請求。

此外,上述標準的靜態資源位置有個例外情況是Webjars內容。任何在/webjars/**路徑下的資源都將從jar文件中提供,只要它們以Webjars的格式打包。

注:如果你的應用將被打包成jar,那就不要使用src/main/webapp文件夾。儘管該文件夾是一個共同的標準,但它僅在打包成war的情況下起作用,並且如果產生一個jar,多數構建工具都會靜悄悄的忽略它。

如果你想刷新靜態資源的緩存,你可以定義一個使用HASH結尾的URL,例如:<link>。

為此,需要使用以下配置:

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

這裡使用了ResourceUrlEncodingFilter過濾器,對於Thymeleaf和Velocity,該過濾器已經自動配置。其他的模板引擎,可以通過ResourceUrlProvider來定義。

當資源文件自動加載的時候,javascript模塊加載器會重命名靜態文件。還有一種“固定”的策略來修改文件名稱。

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
spring.resources.chain.strategy.fixed.enabled=true
spring.resources.chain.strategy.fixed.paths=/js/lib/
spring.resources.chain.strategy.fixed.version=v12

使用了上面的配置之後,當javascript加載"/js/lib/"目錄下的文件時,將會使用一個固定的版本"/v12/js/lib/mymodule.js",而其他的靜態資源仍然使用<link>。

更多說明,參考ResourceProperties,或者閱讀該偏文章。

5.1.5 ConfigurableWebBindingInitializer

Spring MVC使用WebBindingInitializer來為一個特定的請求初始化WebDataBinder。如果你自帶一個了一個ConfigurableWebBindingInitializer @Bean,Spring Boot會自動配置Spring MVC來使用它。

5.1.6 模板引擎

正如REST web服務,你也可以使用Spring MVC提供動態HTML內容。Spring MVC支持各種各樣的模板技術,包括Velocity,FreeMarker和JSPs。很多其他的模板引擎也提供它們自己的Spring MVC集成。

Spring Boot為以下的模板引擎提供自動配置支持:

  • FreeMarker
  • Groovy
  • Thymeleaf
  • Velocity
  • Mustache

注:如果可能的話,應該忽略JSPs,因為在內嵌的servlet容器使用它們時存在一些已知的限制。

當你使用這些引擎的任何一種,並採用默認的配置,你的模板將會從src/main/resources/templates目錄下自動加載。

注:IntelliJ IDEA根據你運行應用的方式會對classpath進行不同的整理。在IDE裡通過main方法運行你的應用跟從Maven或Gradle或打包好的jar中運行相比會導致不同的順序。這可能導致Spring Boot不能從classpath下成功地找到模板。如果遇到這個問題,你可以在IDE裡重新對classpath進行排序,將模塊的類和資源放到第一位。或者,你可以配置模塊的前綴為classpath*:/templates/,這樣會查找classpath下的所有模板目錄。

5.1.7 錯誤處理

Spring Boot默認提供一個/error映射用來以合適的方式處理所有的錯誤,並且它在servlet容器中註冊了一個全局的 錯誤頁面。對於機器客戶端(相對於瀏覽器而言,瀏覽器偏重於人的行為),它會產生一個具有詳細錯誤,HTTP狀態,異常信息的JSON響應。對於瀏覽器客戶端,它會產生一個白色標籤樣式(whitelabel)的錯誤視圖,該視圖將以HTML格式顯示同樣的數據(可以添加一個解析為erro的View來自定義它)。為了完全替換默認的行為,你可以實現ErrorController,並註冊一個該類型的bean定義,或簡單地添加一個ErrorAttributes類型的bean以使用現存的機制,只是替換顯示的內容。

如果在某些條件下需要比較多的錯誤頁面,內嵌的servlet容器提供了一個統一的Java DSL(領域特定語言)來自定義錯誤處理。 示例:

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer(){
return new MyCustomizer();
}
// ...
private static class MyCustomizer implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404"));
container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500"));
}
}
}

你也可以使用常規的Spring MVC特性來處理錯誤,比如@ExceptionHandler方法和@ControllerAdvice。ErrorController將會撿起任何沒有處理的異常。

N.B. 如果你為一個路徑註冊一個ErrorPage,最終被一個過濾器(Filter)處理(對於一些非Spring web框架,像Jersey和Wicket這很常見),然後過濾器需要顯式註冊為一個ERROR分發器(dispatcher)。

@Bean
public FilterRegistrationBean myFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter());
...
registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
return registration;
}

注:默認的FilterRegistrationBean沒有包含ERROR分發器類型。

5.1.8 Spring HATEOAS

如果你正在開發一個使用超媒體的RESTful API,Spring Boot將為Spring HATEOAS提供自動配置,這在多數應用中都工作良好。自動配置替換了對使用@EnableHypermediaSupport的需求,並註冊一定數量的beans來簡化構建基於超媒體的應用,這些beans包括一個LinkDiscoverer和配置好的用於將響應正確編排為想要的表示的ObjectMapper。ObjectMapper可以根據spring.jackson.*屬性或一個存在的Jackson2ObjectMapperBuilder bean進行自定義。

通過使用@EnableHypermediaSupport,你可以控制Spring HATEOAS的配置。注意這會禁用上述的對ObjectMapper的自定義。

5.1.9 CORS支持

你可以在方法上使用@CrossOrigin註解,或者配置一個全局的設置:

@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**");
}
};
}
}

5.2 JAX-RS和Jersey

如果喜歡JAX-RS為REST端點提供的編程模型,你可以使用可用的實現替代Spring MVC。如果在你的應用上下文中將Jersey 1.x和Apache Celtix的Servlet或Filter註冊為一個@Bean,那它們工作的相當好。Jersey 2.x有一些原生的Spring支持,所以我們會在Spring Boot為它提供自動配置支持,連同一個啟動器(starter)。

想要開始使用Jersey 2.x只需要加入spring-boot-starter-jersey依賴,然後你需要一個ResourceConfig類型的@Bean,用於註冊所有的端點(endpoints)。

@Component
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(Endpoint.class);
}
}

所有註冊的端點都應該被@Components和HTTP資源annotations(比如@GET)註解。

@Component
@Path("/hello")
public class Endpoint {
@GET
public String message() {
return "Hello";
}
}

由於Endpoint是一個Spring組件(@Component),所以它的生命週期受Spring管理,並且你可以使用@Autowired添加依賴及使用@Value注入外部配置。Jersey servlet將被註冊,並默認映射到/*。你可以將@ApplicationPath添加到ResourceConfig來改變該映射。

默認情況下,Jersey將在一個ServletRegistrationBean類型的@Bean中被設置成名稱為jerseyServletRegistration的Servlet。通過創建自己的相同名稱的bean,你可以禁止或覆蓋這個bean。你也可以通過設置spring.jersey.type=filter來使用一個Filter代替Servlet(在這種情況下,被覆蓋或替換的@Bean是jerseyFilterRegistration)。該servlet有@Order屬性,你可以通過spring.jersey.filter.order進行設置。不管是Servlet還是Filter註冊都可以使用spring.jersey.init.*定義一個屬性集合作為初始化參數傳遞過去。

這裡有一個Jersey示例,你可以查看如何設置相關事項。

5.3 內嵌的容器支持

5.3.1 Servlets和Filters

當使用內嵌的servlet容器時,你可以直接將servlet和filter註冊為Spring的beans。在配置期間,如果你想引用來自application.properties的值,這是非常方便的。默認情況下,如果上下文只包含單一的Servlet,那它將被映射到根路徑(/)。在多Servlet beans的情況下,bean的名稱將被用作路徑的前綴。過濾器會被映射到/*。

如果基於約定(convention-based)的映射不夠靈活,你可以使用ServletRegistrationBean和FilterRegistrationBean類實現完全的控制。如果你的bean實現了ServletContextInitializer接口,也可以直接註冊它們。

EmbeddedWebApplicationContext

Spring Boot底層使用了一個新的ApplicationContext類型,用於對內嵌servlet容器的支持。EmbeddedWebApplicationContext是一個特殊類型的WebApplicationContext,它通過搜索一個單一的EmbeddedServletContainerFactory bean來啟動自己。通常,TomcatEmbeddedServletContainerFactory,JettyEmbeddedServletContainerFactory或UndertowEmbeddedServletContainerFactory將被自動配置。

注:你通常不需要知道這些實現類。大多數應用將被自動配置,並根據你的行為創建合適的ApplicationContext和EmbeddedServletContainerFactory。

自定義內嵌servlet容器

常見的Servlet容器設置可以通過Spring Environment屬性進行配置。通常,你會把這些屬性定義到application.properties文件中。 常見的服務器設置包括:

  • server.port - 進來的HTTP請求的監聽端口號
  • server.address - 綁定的接口地址
  • server.sessionTimeout - session超時時間

具體參考ServerProperties。

編程方式的自定義

如果需要以編程的方式配置內嵌的servlet容器,你可以註冊一個實現EmbeddedServletContainerCustomizer接口的Spring bean。EmbeddedServletContainerCustomizer提供對ConfigurableEmbeddedServletContainer的訪問,ConfigurableEmbeddedServletContainer包含很多自定義的setter方法。

import org.springframework.boot.context.embedded.*;
import org.springframework.stereotype.Component;
@Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(9000);
}
}

直接自定義ConfigurableEmbeddedServletContainer

如果上面的自定義手法過於受限,你可以自己註冊TomcatEmbeddedServletContainerFactory,JettyEmbeddedServletContainerFactory或UndertowEmbeddedServletContainerFactory。

@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
factory.setPort(9000);
factory.setSessionTimeout(10, TimeUnit.MINUTES);

factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html");
return factory;
}

很多可選的配置都提供了setter方法,也提供了一些受保護的鉤子方法以滿足你的某些特殊需求。具體參考相關文檔。

JSP的限制

在內嵌的servlet容器中運行一個Spring Boot應用時(並打包成一個可執行的存檔archive),容器對JSP的支持有一些限制。

  • tomcat只支持war的打包方式,不支持可執行的jar。
  • 內嵌的Jetty目前不支持JSPs。
  • Undertow不支持JSPs。


分享到:


相關文章: