Spring Applications
SpringApplication: 提供一種便攜的方式來啟動Spring應用(main函數)。 可以使用靜態方法調用 SpringApplication.run
啟動
啟動日志
- Spring啟動日志默認為info級別,可以關閉 spring.main.log-startup-info=false
- FailureAnalyzers 處理啟動時拋出的異常,可以自己實現
- 若仍無analyzer處理異常,則可以使用DEBUG級別的日志,或者啟動時增加debug屬性:
- JAVA -jar *.jar --debug
延遲加載
- 延遲加載默認關閉,開啟有可能導致錯誤延后發現
- 延遲加載開關配置: spring.main.lazy-initialzation=true
- 延遲開關代碼: SpringApplicationBuilder lazyInitialization; SpringApplication setLazyInitialization
- 延遲開關注解: @Lazy(false)
banner
- 類: SpringBootBanner
- 配置文件 banner.txt
- 支持將系統的一些變量輸出
- 代碼設置: SpringApplication.setBanner()
- 開關配置 console/log/off: spring.main.banner-mode=off
- 地址配置:spring.banner.location
自定義Spring Application
- 支持自定義SpringApplication
- @SpringBootApplication
public class MyApplication { public static void main(String[] args) { SpringApplication application = new SpringApplication(MyApplication.class); application.setBannerMode(Banner.Mode.OFF); application.run(args); }}
Builder API
- Springboot應用構建
- new SpringApplicationBuilder()
.sources(Parent.class) .child(Application.class) .bannerMode(Banner.Mode.OFF) .run(args);
應用可用性監控
- Spring boot actuator
- ApplicationAvailability 實現該接口來向外暴露狀態
Liveness State
應用是否存活,與外部狀態無關
Readiness State
應用是否可用(例如CommandLineRunner ApplicationRunner在被執行時)
狀態管理
- 監聽狀態改變
- @Component
public class MyReadinessStateExporter { @EventListener public void onStateChange(AvailabilityChangeEvent<ReadinessState> event) { switch (event.getState()) { case ACCEPTING_TRAFFIC: // create file /tmp/healthy break; case REFUSING_TRAFFIC: // remove file /tmp/healthy break; } }} - 改變狀態
- @Component
public class MyLocalCacheVerifier { private final ApplicationEventPublisher eventPublisher; public MyLocalCacheVerifier(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } public void checkLocalCache() { try { // ... } catch (CacheCompletelyBrokenException ex) { AvailabilityChangeEvent.publish(this.eventPublisher, ex, LivenessState.BROKEN); } }}
應用事件監聽
除了通常的Spring事件, 比如ContextRefreshedEvent, SpringApplication還可以發送其他事件
有些事件在ApplicationContext創建之前觸發,這種無法通過注冊bean來注冊監聽器,可以通過其他方式監聽:
SpringApplication.addListeners()/ SpringApplication.listeners()
支持自動化配置listeners. META_INF/spring.factories
org.springframework.context.ApplicationListener=com.example.MyListener
應用實踐發送順序:
- An ApplicationStartingEvent is sent at the start of a run but before any processing, except for the registration of listeners and initializers.
- An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known but before the context is created.
- An ApplicationContextInitializedEvent is sent when the ApplicationContext is prepared and ApplicationContextInitializers have been called but before any bean definitions are loaded.
- An ApplicationPreparedEvent is sent just before the refresh is started but after bean definitions have been loaded.
- An ApplicationStartedEvent is sent after the context has been refreshed but before any application and command-line runners have been called.
- An AvailabilityChangeEvent is sent right after with LivenessState.CORRECT to indicate that the application is considered as live.
- An ApplicationReadyEvent is sent after any application and command-line runners have been called.
- An AvailabilityChangeEvent is sent right after with ReadinessState.ACCEPTING_TRAFFIC to indicate that the application is ready to service requests.
- An ApplicationFailedEvent is sent if there is an exception on startup.
當ApplicationContext 被刷新后會觸發ContextRefreshedEvent
實現ApplicationContextAware 可注入ApplicationContext
獲取啟動參數
ApplicationArguments
@Component
public class MyBean {
public MyBean(ApplicationArguments args) {
boolean debug = args.containsOption("debug");
List<String> files = args.getNonOptionArgs();
if (debug) {
System.out.println(files);
}
// if run with "--debug logfile.txt" prints ["logfile.txt"]
}
}
ApplicationRunner CommandLineRunner
在SpringApplication啟動之后, 需要運行相關代碼時, 可以用ApplicationRunner或CommandLineRunner。 接口均實現run方法。 區別是ApplicationRunner使用ApplicationArguments, CommandLineRunner使用字符串數組接收請求參數。
若有多個bean被定義并要求有順序執行,可以實現
org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order
應用關閉
每個Spring應用會向JVM注冊一個鉤子確保ApplicationContext可以順利關閉 每個標準Spring生命周期的方法會被調用(例如DisposableBean 或@PreDestroy)
可以指定錯誤碼
org.springframework.boot.ExitCodeGenerator(自定義異常錯誤碼)
SpringApplicaiton.exit()
管理特性
啟動管理功能,支持遠程管理,暴露
SpringApplicationAdminMXBean MBeanServer
spring.application.admin.enabled=true
外部配置
包含Java properties files, yaml files, environment variables, command-line arguments
可通過@Value獲取 或者 結構化對象(通過@ConfigurationProperties)
@value(${name:123})
配置優先級
- Default properties (specified by setting SpringApplication.setDefaultProperties).
- @PropertySource annotations on your @Configuration classes. Please note that such property sources are not added to the Environment until the application context is being refreshed. This is too late to configure certain properties such as logging.* and spring.main.* which are read before refresh begins.
- Config data (such as application.properties files).
- A RandomValuePropertySource that has properties only in random.*.
- OS environment variables.
- Java System properties (System.getProperties()).
- JNDI attributes from java:comp/env.
- ServletContext init parameters.
- ServletConfig init parameters.
- Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
- Command line arguments.
- properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
- @TestPropertySource annotations on your tests.
- Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.
配置文件按以下優先級覆蓋
- Application properties packaged inside your jar (application.properties and YAML variants).
- Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants).
- Application properties outside of your packaged jar (application.properties and YAML variants).
- Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants).
可通過命令行設置配置
使用 -- 前綴
關閉命令行參數
SpringApplication.setAddCommandLineProperties(false)
通過json配置
環境變量: SPRING_APPLICATION_JSON java 啟動命令: -Dspring.application.json
外部配置
通過以下順序:
- classpath
- classpath
- classpath/config
- current dir
- current dir
- current dir/config
修改配置文件名稱 Java啟動命令 --spring.config.name=···
修改配置文件地址 --spring.config.location
--spring.config.additional-location
配置文件地址支持使用通配符* , 支持多個目錄配置文件
環境配置文件 application-{profile}
外部導入
支持外部導入配置文件
spring.config.import=optional:file:./dev.properties
若不支持后綴名可以換寫法:
spring.config.import=optional:file:./dev[.ymal]
配置樹
可支持按文件層級關系做配置
spring.config.import=optional:configtree:/etc/config
占位符
可使用其他配置作為變量 ${app.name}
配置中的隨機變量
支持integer, long, uuid, strings.
${random.value}
${random.int}
${random.long}
${random.uuid}
${random.int(10)}
${random.int[1024, 65536]}
類型安全的配置(使用類配置)
@ConfigurationProperties("") 注意還需要作為一個bean來注入使用
Profiles
任何@Comp.NET, @Configuration, @ConfigurationProperties都可以被@Profile限制。
指定激活profile
spring.profiles.active=dev,hsqldb
spring.profiles.default=none
profile group
profiles
spring.profiles.group.production[0]=proddb
spring.profiles.group.production[1]=prodmq
程序設置profile
SpringApplication.setAdditionalProfiles(...)
Logging
日志格式
- Date and Time: Millisecond precision and easily sortable.
- Log Level: ERROR, WARN, INFO, DEBUG, or TRACE.
- Process ID.
- A --- separator to distinguish the start of actual log messages.
- Thread name: Enclosed in square brackets (may be truncated for console output).
- Logger name: This is usually the source class name (often abbreviated).
- The log message.
日志顏色
%clr 來指定日志顏色
%clr(%5p)
%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}
顏色支持: blue,cyan,faint,green,magenta,red,yellow
文件輸出
日志文件為10MB, 默認輸出ERROR, WARN, INFO logging.file.name logging.file.path
file rotation
- logging.logback.rollingpolicy.file-name-pattern
- The filename pattern used to create log archives.
- logging.logback.rollingpolicy.clean-history-on-start
- If log archive cleanup should occur when the application starts.
- logging.logback.rollingpolicy.max-file-size
- The maximum size of log file before it is archived.
- logging.logback.rollingpolicy.total-size-cap
- The maximum amount of size log archives can take before being deleted.
- logging.logback.rollingpolicy.max-history
- The maximum number of archive log files to keep (defaults to 7).
日志等級
日志級別: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
logging.level.<logger-name>=<level>
logging.level.root=
日志組
spring有預設的日志組 如 web, sql
logging.group.Tomcat=org.Apache.catalina,org.apache.coyote,org.apache.tomcat
logging.level.tomcat=trace
日志關閉鉤子
logging.register-shutdown-hook=false
自定義日志配置
指定自定義日志系統
org.springframework.boot.logging.LoggingSystem=
logback: logback-spring.xml, logback.xml
log4j2: log4j2-spring.xml, log4j2.xml
JDK: logging.properties