內容很長建議收藏後食用.這只是第一波文檔,後續會更上,關注,在看走一波
spring for start
@RestController and @RequestMapping 註解
@RestController 是一個構造性註解,它爲閱讀者提供了標註,對於 Spring 來說這個類扮演者特殊的角色.
@RequestMapping 標註這是一個’路由’,它會告訴 Spring 任何 HTTP 請求都需要印射到不同的’路由’上,@RestController 註解告訴 Spring 對於調用方的返回結果是字符串的
@RestController and @RequestMapping 並不是 Spring Boot 獨有的,詳細可以參考 Spring 中的
MVC section部分
@EnableAutoConfiguration 註解
第二類級別的註解就是 @EnableAutoConfiguration,這個註釋告訴 Spring Boot 根據添加的 jar 依賴關係“猜測”您將如何配置 Spring spring-boot-starter-web
計入了 Tomcat 和 Spring MVC,自動配置默認認爲你在開發一個 Spring 的 web 項目
main 方法
應用的最後一個部分就是main
方法,這只是一個遵循 Java 約定程序入口點的標準方法,SpringApplication 由 mian 方法中的 run 代理,SpringApplication 就會引導我們的應用,啓動 Spring 會反向自動配置 Tomcat web 服務.我們需要類的 run 方法來告訴 SpringApplication 誰纔是 Spring 的主要組件.args 數組也可以傳入任意的命令行參數.
可執行的 jar
通常我們會把所有的依賴 jar 打入一個 jar 之中,但是可能會出現相同 jar 包名,但是內容不相同的問題,Spring 採用了多種方式,允許在實際中直接嵌套 jar.
創建一個可執行的 jar 需要在 pom.xml 文件中引入spring-boot-maven-plugin
,如果你未使用spring-boot-starter-parent
,你需要重新配置,可以參考plugin
文檔
你可以使用mvn package
進行打包.之後你會在target
目錄下看見項目名稱-0.0.1-SNAPSHOT.jar
,如果你想查看 jar 內部內容,可以使用jar tvf
,你可以看見更小的文件***-0.0.1-SNAPSHOT.jar.original
在target
目錄下,這個文件就是 Maven 在 Spring Boot 重新打包之前創建的原始 jar 文件
使用 Spring Boot
依賴管理
SPring Boot 每個版本都提供了精緻的依賴,你不需要在構建配置中爲這些依賴提供任何版本,因爲 Spring Boot 會爲你管理版本,當你升級 Spring Boot 這些依賴會一起升級.
如果你覺得有必要的話,你也可以強行覆蓋這個版本依賴
Spring Boot 的依賴包含了所有 spring 模塊和完善的一些三方庫.
每個Spring Boot版本都與Spring Framework 的基本版本有關聯,所以強烈建議不要自行指定其版本
Maven
Maven 用戶可以從spring-boots-starter-parent
中獲得默認配置,它會提供如下功能
- Java 1.8 是默認的編譯器級別
- UTF-8 是默認的編碼
- 允許你忽略從
spring-boot-dependencies
繼承來的依賴的<version>
標籤 - 智能的資源過濾
- 智能的插件配置 (shade,surefire …)
- 從
application.properties
和application.yml
智能過濾資源或者其他的一些文件(application-foo.properties
和application.properties.yml
)
最後一點:由於默認的配置文件支持 Spring 樣式的佔位符${..}
,所以 Maven 的過濾器使用@..@
佔位符.(你也可以使用 Maven 的 resource.delimilter 覆蓋它)
繼承啓動類父類依賴 pom 使用 Spring Boot
只需要將spring-boot-starter-parent
設置爲 pom 中的父類依賴
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M3</version>
</parent>
必須指定Spring Boot啓動器版本,除非你已經引入其它版本的啓動器
這是 spring-boot-dependencies
的 pom
無需依賴啓動類父類依賴來使用 Spring Boot
如果你不想使用spring-boot-starter-parent
,你還可以使用依賴管理的scope=import
來管理依賴
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.0.0.M3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
使用 spring-boot-maven-plugin
Spring Boot 包含一個 Maven 插件,可以把項目打包成可以執行的 jar.如果要使用插件,請將其它添加到<plugins>
中
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
如果你使用的是spring-boot-starter-parent,你無需配置此插件,除非你想覆蓋它的一些設置
Starter (入門程序)
入門程序包含了許多快速使用並且啓動的依賴項.並且各自有一組支持傳遞依賴的依賴
所有的官方入門程序都遵循 spring-boot-starter-*的命名方式
以下是 Spring 官方提供的 Starter
Name | Description | Pom |
---|---|---|
Core starter, including auto-configuration support, logging and YAML | ||
Starter for JMS messaging using Apache ActiveMQ | ||
Starter for using Spring AMQP and Rabbit MQ | ||
Starter for aspect-oriented programming with Spring AOP and AspectJ | ||
Starter for JMS messaging using Apache Artemis | ||
Starter for using Spring Batch | ||
Starter for using Spring Framework’s caching support | ||
Starter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku | ||
Starter for using Cassandra distributed database and Spring Data Cassandra | ||
Starter for using Cassandra distributed database and Spring Data Cassandra Reactive | ||
Starter for using Couchbase document-oriented database and Spring Data Couchbase | ||
Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch | ||
Starter for using Spring Data JPA with Hibernate | ||
Starter for using Spring Data LDAP | ||
Starter for using MongoDB document-oriented database and Spring Data MongoDB | ||
Starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive | ||
Starter for using Neo4j graph database and Spring Data Neo4j | ||
Starter for using Redis key-value data store with Spring Data Redis and the Jedis client | ||
Starter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client | ||
Starter for exposing Spring Data repositories over REST using Spring Data REST | ||
Starter for using the Apache Solr search platform with Spring Data Solr | ||
Starter for building MVC web applications using FreeMarker views | ||
Starter for building MVC web applications using Groovy Templates views | ||
Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS | ||
Starter for using Spring Integration | ||
Starter for using JDBC with the Tomcat JDBC connection pool | ||
Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to | ||
Starter for using jOOQ to access SQL databases. An alternative to | ||
Starter for JTA transactions using Atomikos | ||
Starter for JTA transactions using Bitronix | ||
Spring Boot Narayana JTA Starter | ||
Starter for using Java Mail and Spring Framework’s email sending support | ||
Starter for building web applications using Spring Mobile | ||
Starter for building web applications using Mustache views | ||
Spring Boot Quartz Starter | ||
Starter for using Spring Security | ||
Starter for using Spring Social Facebook | ||
Stater for using Spring Social LinkedIn | ||
Starter for using Spring Social Twitter | ||
Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito | ||
Starter for building MVC web applications using Thymeleaf views | ||
Starter for using Java Bean Validation with Hibernate Validator | ||
Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container | ||
Starter for using Spring Web Services | ||
Starter for building WebFlux applications using Spring Framework’s Reactive Web support | ||
Starter for building WebSocket applications using Spring Framework’s WebSocket support |
除了這些入門程序,Spring同樣也提供一些準備生產的版本
Name | Description | Pom |
---|---|---|
Starter for using Spring Boot’s Actuator which provides production ready features to help you monitor and manage your application |
Spring 也提供了一些啓動器
Name | Description | Pom |
---|---|---|
Starter for using Jetty as the embedded servlet container. An alternative to | ||
Starter for reading and writing json | ||
Starter for using Log4j2 for logging. An alternative to | ||
Starter for logging using Logback. Default logging starter | ||
Starter for using Reactor Netty as the embedded reactive HTTP server. | ||
Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by | ||
Starter for using Undertow as the embedded servlet container. An alternative to |
更多spring-boot-starter模塊文檔,可以參考README file
結構化代碼
spring Boot不需要任何結構化代碼就可以直接使用.
使用 ‘default’ 包
當一個程序不包含一個package
時,它會被默認爲是在default package
中,通常不鼓勵使用default package
.對於@ComponentScan
,@EntityScan
,@SpringBootApplication
註解的Spring Boot應用,會導致特定的問題,因爲每個jar都會被讀取
建議遵循Java的程序包命名約定(反向域名.例如:com.example.project)
查找應用入口
通常建議主程序應用入口(啓動類)放在項目根目錄下.@EnableAutoConfiguration
通常放在主類上,它隱式定義了一些項目的search package
在根目錄下使用@ComponentScna
註解,無需指定basePackage
屬性.如果在主類在根目錄下,也可以使用@SpringApplication
註解
以下是一個經典佈局
com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java
Application.java將聲明main
方法和基本的@Configuration
package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
配置類
Spring Boot 支持基於java的配置.儘管SpringApplication
可以和XML
一起使用,但是通常建議主要來源使用單個的@Configuration
類.通常定義main
方法的類也是主要的@Configuration
網上有很多使用XML配置Spring的實例.但是如果有可能,儘量嘗試使用等效的基於Java的配置. 搜索Enable.* 可能會是一個好的起點
導入其他配置類
無需將所有的@Configuration
放在一個類中.@Import
註解可用於導入其他配置類.你也可以使用@ComponentScan
自動拾取Spring組件,其中包括了@Configuration
類.
導入XML配置
如果要使用XML配置,我們建議仍從@Configuration
類開始.然後,可以使用@ImportResource
註解來加載XML配置文件.
自動配置
Spring Boot 自動配置會嘗試根據添加的jar依賴項自動配置Spring應用.
你需要通過給@Configuration
類加上@EnableAutoConfiguration
或者@SpringApplication
來自動裝載配置
你應該只添加一個@EnableAutoConfiguration
在你的應用中,通常我們建議添加到主類中.也就是啓動類`.
逐漸取消自動配置
自動配置是非侵入性的,你可以隨時使用自定義配置來替換它特定的部分.
如果你想知道應用使用了哪些自動配置,可以使用-- debug
開關啓動你的應用程序,控制檯會輸出自動配置的報告記錄.
禁用特定的自動配置
如果你有不需要的自動配置,你可以通過@EnableAutoConfiguration
中的exclude
屬性將其禁用.
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}
如果類不在類路徑中,則可以使用excludeName
屬性,並指定完整的路徑名稱.最後,你還可以通過配置文件中的spring.autoconfigure.exclude
屬性控制要配出的自動配置類列表
Spring Beans 和依賴注入
我們可以使用@ComponentScan
來需找你的beans,並結合@Autowired
使用構造函數注入效果會更好
如果你按上述建議構建了代碼(將應用程序類放在根目錄下),你可以添加一個不帶任何參數的@ComponentScan
,你的所有的組件(@Component
,@Service
,@Repository
,@Controller
等)都將會自動註冊爲Spring Bean
package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
@Autowired
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
@Service
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
需要注意的是構造函數的方法來注入
@Service
public class AccountService {
private final UserService userService;
private final PermissionService permissionService;
private final CacheManager cacheManager;
public AccountService(final UserService userService, final PermissionService permissionService, final CacheManager cacheManager) {
this.userService = userService;
this.permissionService = permissionService;
this.cacheManager = cacheManager;
}
}
使用 @SpringApplication 註解
許多Spring Boot 開發人員主類總是帶有@Configuration
, @EnableAutoConfiguration
和 @ComponentScan
. 這幾個註解通常會一起使用,因爲我們提供了一中方便的@SpringApplication
註解
@SpringApplication
包含的這些所有的註解
package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.annotation.AliasFor;
import org.springframework.data.repository.Repository;
/**
* Indicates a {@link Configuration configuration} class that declares one or more
* {@link Bean @Bean} methods and also triggers {@link EnableAutoConfiguration
* auto-configuration}, {@link ComponentScan component scanning}, and
* {@link ConfigurationPropertiesScan configuration properties scanning}. This is a
* convenience annotation that is equivalent to declaring {@code @Configuration},
* {@code @EnableAutoConfiguration}, {@code @ComponentScan}.
*
* @author Phillip Webb
* @author Stephane Nicoll
* @author Andy Wilkinson
* @since 1.2.0
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
/**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
@AliasFor(annotation = EnableAutoConfiguration.class)
Class<?>[] exclude() default {};
/**
* Exclude specific auto-configuration class names such that they will never be
* applied.
* @return the class names to exclude
* @since 1.3.0
*/
@AliasFor(annotation = EnableAutoConfiguration.class)
String[] excludeName() default {};
/**
* Base packages to scan for annotated components. Use {@link #scanBasePackageClasses}
* for a type-safe alternative to String-based package names.
* <p>
* <strong>Note:</strong> this setting is an alias for
* {@link ComponentScan @ComponentScan} only. It has no effect on {@code @Entity}
* scanning or Spring Data {@link Repository} scanning. For those you should add
* {@link org.springframework.boot.autoconfigure.domain.EntityScan @EntityScan} and
* {@code @Enable...Repositories} annotations.
* @return base packages to scan
* @since 1.3.0
*/
@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
String[] scanBasePackages() default {};
/**
* Type-safe alternative to {@link #scanBasePackages} for specifying the packages to
* scan for annotated components. The package of each class specified will be scanned.
* <p>
* Consider creating a special no-op marker class or interface in each package that
* serves no purpose other than being referenced by this attribute.
* <p>
* <strong>Note:</strong> this setting is an alias for
* {@link ComponentScan @ComponentScan} only. It has no effect on {@code @Entity}
* scanning or Spring Data {@link Repository} scanning. For those you should add
* {@link org.springframework.boot.autoconfigure.domain.EntityScan @EntityScan} and
* {@code @Enable...Repositories} annotations.
* @return base packages to scan
* @since 1.3.0
*/
@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
Class<?>[] scanBasePackageClasses() default {};
/**
* Specify whether {@link Bean @Bean} methods should get proxied in order to enforce
* bean lifecycle behavior, e.g. to return shared singleton bean instances even in
* case of direct {@code @Bean} method calls in user code. This feature requires
* method interception, implemented through a runtime-generated CGLIB subclass which
* comes with limitations such as the configuration class and its methods not being
* allowed to declare {@code final}.
* <p>
* The default is {@code true}, allowing for 'inter-bean references' within the
* configuration class as well as for external calls to this configuration's
* {@code @Bean} methods, e.g. from another configuration class. If this is not needed
* since each of this particular configuration's {@code @Bean} methods is
* self-contained and designed as a plain factory method for container use, switch
* this flag to {@code false} in order to avoid CGLIB subclass processing.
* <p>
* Turning off bean method interception effectively processes {@code @Bean} methods
* individually like when declared on non-{@code @Configuration} classes, a.k.a.
* "@Bean Lite Mode" (see {@link Bean @Bean's javadoc}). It is therefore behaviorally
* equivalent to removing the {@code @Configuration} stereotype.
* @since 2.2
* @return whether to proxy {@code @Bean} methods
*/
@AliasFor(annotation = Configuration.class)
boolean proxyBeanMethods() default true;
}
@SpringBootApplication還提供別名以自定義@EnableAutoConfiguration和@ComponentScan的屬性。
啓動你的應用
將應用程序打包爲jar並使用嵌入式HTTP服務器是Spring Boot最大優勢之一.
啓動你的打包應用
java -jar target/myproject-0.0.1-SNAPSHOT.jar
也可以在啓用了遠程調試支持的情況下運行打包的應用程序。這使您可以將調試器附加到打包的應用程序:
java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \
-jar target/myproject-0.0.1-SNAPSHOT.jar
使用Maven Plugin
Spring Boot Maven插件包含一個運行目標,可用於快速編譯和運行您的應用程序。應用程序以爆炸形式運行,就像在IDE中一樣。
mvn spring-boot:run
您可能還想使用有用的操作系統環境變量:
export MAVEN_OPTS=-Xmx1024m
Spring Boot 的功能
@SpringApplication
SpringApplication 提供了便捷的啓動方式,將使用main()方法來啓動Spring應用,大多數情況下只能委託給SpringApplication.run方法
public static void main(String[] args) {
SpringApplication.run(MySpringConfiguration.class, args);
}
啓動失敗
如果啓動失敗,已註冊的FailureAnalyzers
將會有機會提供專門的錯誤消息和解決該問題的具體措施
***************************
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 提供了大量的FailureAnalyzers
實現,你可以輕鬆的添加
自己的實現
如果錯誤分析器沒有捕獲異常,你任然可以顯示完整的自動配置的報告,可以讓你更好了解發生了什麼問題.
你需要爲org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer
啓動debug
屬性或者啓動DEBUG
日誌記錄
如果你使用的是java -jar
來啓動應用,你可以添加debug
屬性
$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug
自定義Banner
你可以通過添加banner.txt文件到你的項目路徑來更換應用啓動時打印的logo.或者設置banner.location
指向你的文件位置.(如果出現文件編碼異常,可以使用banner.charset
來設置.默認爲UTF-8
).除了txt
文件外,還可以將圖像文件gif
,jpg
,png
添加到項目路徑或者設置banner.image.location
屬性.這些圖片將會轉化爲ASCII
藝術作品並打印在任何文字上方.
在banner.txt
你可以使用以下任意佔位符
Variable | Description |
---|---|
| The version number of your application as declared in |
| The version number of your application as declared in |
| The Spring Boot version that you are using. For example |
| The Spring Boot version that you are using formatted for display (surrounded with
brackets and prefixed with |
| Where |
| The title of your application as declared in |
如果你使用代碼的方式實現Banner
,你可以使用SpringApplication.setBanner()
.也可以使用org.springframework.boot.Banner
接口實現你的printBanner()
方法
您還可以使用spring.main.banner-mode
屬性來確定是否必須使用配置的記錄器(log
)將橫幅打印在System.out(console
)上,或者根本不打印(off
)
YAML的設置
spring:
main:
banner-mode: "off"
自定義的SpringApplication
如果你不喜歡SpringApplication的默認設置,你也可以創建一個本地實例來啓動Spring Boot應用
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MySpringConfiguration.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
這裏傳遞給SpringApplication的構造函數式Spring Bean的配置源.通常情況下它將是對@Configuration
類的引用,或者是XML的配置或者是應掃描的包引用
同樣我們也可以使用application,properties
文件來配置SpringApplication.詳細請參照
Chapter 24, Externalized Configuration 外部化配置.
有關配置選項的完整列表,請參見SpringApplication
Javadoc
流式構建 API
如果你需要構建ApplicationContext層級結構(具有父/子關係的多個上下文),或者只是喜歡流式構造的API,則可以使用SpringApplicationBuilder
SpringApplicationBuilder
允許將多個方法調用鏈接在一起,並允許創建層次結構的父方法和子方法
new SpringApplicationBuilder()
.sources(Parent.class)
.child(Application.class)
.bannerMode(Banner.Mode.OFF)
.run(args);
創建ApplicationContext層級結構的時候會有一些限制,例如:Web組件必須包含在子上下文中,並且相同的環境將用於父上下文和子上下文.更多纖細請看SpringApplicationBuilder
Javadoc
Application 的事件和監聽器
除了通產的Spring Framework事件(例如:ContextRefreshedEvaent)之外,SpringApplication還發送一些其他的application事件
實際上在創建ApplicationContext
之前會觸發一些事件,所以你不能這些監聽器爲@Bean
,你可以通過SpringApplication.addListeners(..)
或者SpringApplicationBuilder.listeners(..)
方法註冊它們.如果你不想管應用程序如何自動註冊那些監聽器.你可以使用1META-INF / spring.factories1文件添加到項目中,並使用1org.springframework.context.ApplicationListener1鍵引用您的監聽器。
org.springframework.context.ApplicationListener=com.example.project.MyListener
應用的事件必須按下列順序發送
- ApplicationStartingEvent .在運行開始時發送,但是在有任何操作之前,除了監聽器和初始化註冊器的初始化之外.
- ApplicationEnvironmentPreparedEvent 需要在一直上下文的Environment中使用,但是需要上下文已經創建
- ApplicationPreparedEvnet 在刷新開始之前但是在Bean定義加載之後發送
- ApplicationReadyEvent 在刷新並處理所有的相關回調後,應用程序已準備好處理請求後發送
- ApplicationFailedEvent 在應用啓動失敗時發送
通常不需要使用應用程序事件,但是瞭解它們的存在可以讓你對Spring Boot的內部更加了解
web 環境
SpringApplication 將會創建正確類型的ApplicationContext.在默認情況下,將使用AnnotationConfiguApplication
或者 AnnotaionConfigServletWebApplicationContext
,具體取決於是否是web應用
確定是否web 環境
所使用的的算法非常簡單,如果你需要調整默認值你可以使用setWebEnvironment(boolean webEnvironment)
,也可以使用setApplicationContextClass(...)
來控制ApplicationContext
的類型
通常在JUnit測試中使用Application時,可以使用setWebEnvironment(false)
訪問應用參數
如果你需要傳遞參數給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"]
}
}
Spring Boot 還將在Spring Environment
中註冊一個CommandLinePropertySource
,它允許你使用@Value
註解來注入單個應用參數
使用SpringApplicationRunner 或者 CommandLineRunner
如果你需要在SpringApplication啓動完成之前加載一些代碼,你尅實現ApplicationRunner
接口或者CommandLineRunner
接口,並實現一個run
方法,它會在SpringApplication.run(...)
完成之前被調用
CommandLineRunner
接口使用的是簡單的字符串數組提供對應用程序的參數的訪問,而ApplicationRunner
接口使用的是ApplicationArguments
接口
import org.springframework.boot.*
import org.springframework.stereotype.*
@Component
public class MyBean implements CommandLineRunner {
public void run(String... args) {
// Do something...
}
}
如果定義了幾個必須按特定順序調用的CommandLineRunner
或ApplicationRunner
Bean,則可以另外實現org.springframework.core.Ordered
接口或使用org.springframework.core.annotation.Order
註釋。
結束應用
爲確保ApplicationContext在退出時正常關閉,每個SpringApplication
都會向JVM註冊一個關閉鉤子.所有的標準Spring生命週期回調都可以使用.(例如:DisposableBean
接口或者@PreDestroy
註解)
@SpringBootApplication
public class ExitCodeApplication {
@Bean
public ExitCodeGenerator exitCodeGenerator() {
return () -> 42;
}
public static void main(String[] args) {
System.exit(SpringApplication
.exit(SpringApplication.run(ExitCodeApplication.class, args)));
}
}
另外,ExitCodeGenerator
接口可以通過異常實現。遇到此類異常時,Spring Boot將返回已實現的getExitCode()
方法提供的退出代碼。
管理員功能
應用管理員功能可以通過指定spring.application.admin.enabled
屬性來管理.在公開平臺MBeanServer
上的SpringApplicationAdminMXBean
。您可以使用此功能來遠程管理Spring Boot應用程序。
如果你想知道應用程序在HTTP哪個端口上運行可以輸入local.server.prot
MBean會公開一鐘關閉應用程序的方法,請小心使用
外部配置
Spring Boot 允許外部配置,以便可以再不同的環境中使用相同的應用程序.你可以使用屬性文件,YANL文件,環境變量和命令行參數來進行操作外部配置
可以使用@Value
註解將屬性直接注入到bean中,還可以通過Spring的抽象環境,也可以通過@ConfigurationProperties
綁定到結構化對象
Spring Boot 使用一個非常特殊的PropertySource順序,你需要按下列的順序來合理覆蓋值
-
您的主目錄上的Devtools全局設置屬性(在devtools處於活動狀態時,爲〜/ .spring-boot-devtools.properties)
-
測試時使用的@TestPropertySource註解。
-
測試時使用的@TestPropertySource#properties註解。
-
命令行參數
-
來自SPRING_APPLICATION_JSON的屬性(嵌入在環境變量或系統屬性中的內聯JSON)
-
ServletConfig 初始化參數
-
ServletContext 初始化參數
-
來自
java:comp/env
的JDNI參數 -
Java系統屬性(System.getProperties())
-
操作系統環境變量
-
一個
RandomValuePropertySource
,它只有一個配置在random.*
裏 -
打包的jar之外的配置文件(application- {profile} .properties和YAML變體)
-
打包的jar包之內的配置文件(application- {profile} .properties和YAML變體)
-
打包的jar之外的應用程序屬性(application.properties和YAML變體)
-
打包在jar中的應用程序屬性(application.properties和YAML變體)
-
在
@Configuration
類上的@Properties
註解 -
默認屬性 (使用
SpringApplication.setDefaultProperties
指定)
假設您開發了一個使用name屬性的@Component
import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.*
@Component
public class MyBean {
@Value("${name}")
private String name;
// ...
}
在你的應用程序的路徑上(例如:在jar中),你可以使用application.properties
來給name
設置一個默認值.在新環境中運行時,可以在jar外部提供application.properties
,以覆蓋name
.你也可以在啓動命令時添加一個臨時參數java -jar app.jar --name="Spring"
SPRING_APPLICATION_JSON 在UNIX中的配置
SPRING_APPLICATION_JSON='{"foo":{"bar":"spam"}}' java -jar myapp.jar
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
配置隨機值
RandomValuePropertySource可用於注入隨機值(例如,注入機密或測試用例)。它可以產生整數,longs,uuid或字符串
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
訪問命令行屬性
默認情況下,SpringApplication
會將所有命令行選項參數(以“-”開頭,例如–server.port = 9000)轉換爲屬性,並將其添加到Spring Environment
中,命令行屬性始終優先於其他屬性源
如果您不希望將命令行屬性添加到環境中,則可以使用SpringApplication.setAddCommandLineProperties(false)
來禁用他們
屬性文件
SpringApplication
將在以下位置從application.properties
文件加載屬性,並將其添加到Spring Environment
中 (注意優先級也如下)
-
當前目錄的
/config
的子目錄 -
當前目錄
-
類路徑
/config
包 -
根路徑
您也可以使用YAML(.yml)文件來替代.properties
你也可以使用spring.config.name
和spring.config.location
來配置你的環境變量
$ java -jar myproject.jar --spring.config.name=myproject
//或者
$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
spring.config.name
和spring.config.location
加載的順序比較早,所以需要確定加載哪些文件,這些就必須要定義爲環境變量(通常爲系統換將變量,系統屬性或者命令行參數)
如果spring.config.name
之後跟的是目錄(不是文件),那就應該是 /
結尾.spring.config.location
中指定的文件按原樣使用,不支持特定於配置文件的變體,並且將被任何特定於配置文件的屬性覆蓋。
配置的位置的搜索順序相反.默認情況下是classpath:/,classpath:/config/,file:./,file:./config/
.而實際上的搜索順序爲
1.file:./config/
2.file:./
3.classpath:/config/
4.classpath:/
在自定義配置後,除了默認位置的順序,還會使用以上順序,在默認位置之前搜索自定義位置。例如,如果配置了自定義位置classpath:/ custom-config /,file:./ custom-config /
,則搜索順序變爲:
1.file:./custom-config/
2.classpath:custom-config/
3.file:./config/
4.file:./
5.classpath:/config/
6.classpath:/
通過此搜索順序,您可以在一個配置文件中指定默認值,然後在另一個配置文件中有選擇地覆蓋這些值
配置文件的特殊屬性
可以使使用application-{profile}.properties
的命名方式給application.properties
定義.如果未定義將會以默認方式application-default.properties
加載
所有的配置都是後來的覆蓋前面的(後贏策略)
如果您在spring.config.location
中指定了任何文件,則不會考慮這些文件的任何特殊屬性。如果您還想使用配置文件的特殊屬性,請使用spring.config.location
中的目錄。
屬性中的佔位符
使用application.properties
中的值時,它們會通過現有環境進行過濾,因此您可以引用以前定義的值(例如,從System屬性中)。
app.name=MyApp
app.description=${app.name} is a Spring Boot application
您還可以使用這種技術來創建現有Spring Boot
屬性的“Short”變體。有關詳細信息,請參見Section 73.4, “Use ‘short’ command line arguments”
使用YAML文件
YAML 是JSON的超集,因此是指定分層配置數據的一中非常方便的格式.只要在應用類路徑上有Snake YAML
庫就會自動支持YAML作爲屬性的替代方法.
spring-boot-starter
將自動提供SnakeYAML
加載YAML
Spring Framework
提供了兩個類來加載YAML文檔.YamlPropertiesFactoryBean
就會把YAML當做一個屬性加載,YamlMapFactoryBean
就會把YAMl當做地圖加載
environments:
dev:
url: http://dev.bar.com
name: Developer Setup
prod:
url: http://foo.bar.com
name: My Cool App
以上配置將會被轉換爲
environments.dev.url=http://dev.bar.com
environments.dev.name=Developer Setup
environments.prod.url=http://foo.bar.com
environments.prod.name=My Cool App
YAML列表用[index]解引用器表示爲屬性鍵,例如,以下YAML
my:
servers:
- dev.bar.com
- foo.bar.com
轉化後
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com
要綁定到使用Spring DataBinder
實用程序的屬性(@ConfigurationProperties
所做的工作),您需要在類型爲java.util.List
(或Set
)的目標bean中具有一個屬性,或者您需要提供一個setter
@ConfigurationProperties(prefix="my")
public class Config {
private List<String> servers = new ArrayList<String>();
public List<String> getServers() {
return this.servers;
}
}
YAML如果配置Spring的環境變量
YamlPropertiesSourceLoader
類可以使用YAML作爲配置源來適用各種Spring環境.它允許使用@Value
註解和佔位符語法來訪問YAML屬性.
server:
address: 192.168.1.100
---
spring:
profiles: development
server:
address: 127.0.0.1
---
spring:
profiles: production
server:
address: 192.168.1.120
如上述配置,當spring.profiles
爲開發,生產或者默認時,server.address
將會採取不同的ip地址
YAML的缺點
無法通過@PropertySource
註釋加載YAML文件。因此,如果您需要以這種方式加載值,則需要使用屬性文件
合併YAML列表
YAML的任何內容都會被轉換爲屬性.
例如,假設MyPojo對象的名稱和描述屬性默認爲空。讓我們從FooProperties中公開MyPojo的列表:
@ConfigurationProperties("foo")
public class FooProperties {
private final List<MyPojo> list = new ArrayList<>();
public List<MyPojo> getList() {
return this.list;
}
}
我們擁有以下配置
foo:
list:
- name: my name
description: my description
---
spring:
profiles: dev
foo:
list:
- name: my another name
在多個配置文件中指定一個集合時,將使用優先級最高的一個(並且僅使用那個)
如果未指定Spring應用的環境爲dev,那麼就會使用默認配置,也就是foo
的name
爲my another name
安全類型屬性的配置
使用@Value
註解來批量注入屬性通常會很麻煩.特別是你使用多個屬性貨數據本質上分層的.Spring Boot提供了一種使用屬性的替代方法,該方法允許強類型的Bean來管理和驗證應用程序的配置.
package com.example;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("foo")
public class FooProperties {
private boolean enabled;
private InetAddress remoteAddress;
private final Security security = new Security();
public boolean isEnabled() { ... }
public void setEnabled(boolean enabled) { ... }
public InetAddress getRemoteAddress() { ... }
public void setRemoteAddress(InetAddress remoteAddress) { ... }
public Security getSecurity() { ... }
public static class Security {
private String username;
private String password;
private List<String> roles = new ArrayList<>(Collections.singleton("USER"));
public String getUsername() { ... }
public void setUsername(String username) { ... }
public String getPassword() { ... }
public void setPassword(String password) { ... }
public List<String> getRoles() { ... }
public void setRoles(List<String> roles) { ... }
}
}
您還需要列出要在@EnableConfigurationProperties
批註中註冊的屬性類:
@Configuration
@EnableConfigurationProperties(FooProperties.class)
public class MyConfiguration {
}
其實這個東西就有點像代理模式,不允許隨便使用配置文件中的配置屬性,它必須通過具有@EnableConfigurationProperties
批註中註冊的屬性類來註冊
第三方配置
除了使用ConfigurationProperties
註解之外,還可以使用@Bean
註解在公共的方法在.這會在使用三方屬性時起到作用
@ConfigurationProperties(prefix = "bar")
@Bean
public BarComponent barComponent() {
...
}
bar前綴定義的任何屬性都將以與上面的FooProperties
示例類似的方式映射到該BarComponent bean
自由的綁定
Spring Boot使用一些簡單的規則將環境屬性綁定到@ConfigurationProperties
bean.因此,環境屬性名稱和Bean屬性名稱之間不比完全匹配.常使用虛線分割(例如:context-path綁定到contextPath)和大小寫區分
例如:
@ConfigurationProperties(prefix="person")
public class OwnerProperties {
private String firstName;
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
Property | Note |
---|---|
| 標準的駝峯語法. |
| Kebab-case,建議在 |
| 下劃線表示法, 用於 |
| 大寫格式。在使用系統環境變量時推薦使用. |
prefix
值的前綴必須是 Kebab-case
,必須由小寫字母開頭和 -
分隔
每個配置源的綁定規則
Table 24.2. relaxed binding rules per property source
Property Source | Simple | List |
---|---|---|
Properties Files | Camel-case, kebab-case or underscore notation | Standard list syntax using |
YAML Files | Camel-case, kebab-case or underscore notation | Standard YAML list syntax or comma-separated values |
Environment Variables | Upper case format with underscore as the delimiter. | Numeric values surrounded by underscores. eg: |
System properties | Camel-case, kebab-case or underscore notation | Standard list syntax using |
我們建議,如果可能,屬性以小寫的kebab格式存儲。即 my.property-name = foo
屬性轉換
當Spring綁定到@ConfigurationProperties
bean時,它將嘗試將外部應用程序屬性強制爲正確的類型。
如果需要自定義類型轉換,則可以提供一個ConversionService
bean(具有bean id conversionService
)或自定義屬性編輯器(通過CustomEditorConfigurer
bean)或者定製轉換器(bean定義標註爲@ConfigurationPropertiesBinding
)
在應用的生命週期中ConversionService
很早就被請求,請注意使用的依賴項.通常,您需要的任何依賴項可能在創建時未完全初始化.如果配置鍵強制不需要自定義的轉換服務,而您只想重命名具有@ConfigurationPropertiesBinding
的自定義轉換器,則可能需要重命名自定義的轉換服務
@ConfigurationProperties驗證
如果使用@Validated
配合@ConfigurationProperties
一起使用時Spring Boot將會對其驗證.
您可以在配置類上直接使用JSR-303 javax.validation約束註釋。只需確保您的類路徑上有兼容的JSR-303實現即可
@ConfigurationProperties(prefix="foo")
@Validated
public class FooProperties {
@NotNull
private InetAddress remoteAddress;
// ... getters and setters
}
當你需要組合嵌套效驗時,必須將使用@Valid
註解才能觸發:
@ConfigurationProperties(prefix="connection")
@Validated
public class FooProperties {
@NotNull
private InetAddress remoteAddress;
@Valid
private final Security security = new Security();
// ... getters and setters
public static class Security {
@NotEmpty
public String username;
// ... getters and setters
}
}
你也可以創建一個名爲configurationPropertiesValidator
的bean來自自定義Spring Validator.這個@Bean
方法必須爲靜態的.配置豎向驗證器是在應用程序生命週期早期創建的,並且將@Bean
方法聲明爲允許靜態創建bean,所以無需實例化@Configuration
類
spring-boot-actuator
模塊包括一個公開所有@ConfigurationProperties
bean的端點。只需將您的Web瀏覽器指向/ configprops
或使用等效的JMX端點即可。請參閱Production ready features。詳細信息
@ConfigurationProperties 和@Value
@Value
是核心容器功能,它沒有提供與類型安全的配置屬性相同的功能。下表總結了@ConfigurationProperties
和@Value
支持的功能
Feature | @ConfigurationProperties | @Value |
---|---|---|
Yes | No | |
Yes | No | |
| No | Yes |
如果您爲自己的組件定義了一組配置鍵,我們建議您將它們組合在以@ConfigurationProperties
註解的POJO中。
另請注意,由於@Value不支持簡單的綁定,因此如果您需要使用環境變量來提供值,則不是一個很好的選擇
最後,儘管您可以在@Value中編寫SpEL表達式,但不會從Application
property files中處理此類表達式。
Profiles(輪廓, 剖面, 側面)
Spring Profiles提供了一種分離應用程序配置的部分並使之僅在某些環境中可用的方法.任何@Component
或@Configuration
都可以用@Profile
標記,以限制加載時間:
@Configuration
@Profile("production")
public class ProductionConfiguration {
// ...
}
以正常的Spring方式,您可以使用spring.profiles.active
的 Environment
屬性指定哪些配置文件處於活動狀態。您可以通過任何常用方式指定屬性,例如,可以將其包含在application.properties
中:
spring.profiles.active=dev,hsqldb
或使用命令行上指定--spring.profiles.active = dev,hsqldb
開關
添加活動配置文件
spring.profiles.active
屬性遵循與其他屬性相同的排序規則,級別最高的PropertySource
將獲勝。這意味着您可以在application.properties
中指定活動配置文件,然後使用命令行開關替換它們。
例如,當使用開關--spring.profiles.active = prod
運行具有以下屬性的應用程序時,proddb
和prodmq
配置文件也將被激活:
---
my.property: fromyamlfile
---
spring.profiles: prod
spring.profiles.include:
- proddb
- prodmq
可以在YAML文檔中定義spring.profiles
屬性,以確定何時將該特定文檔包括在配置中。有關更多詳細信息,請參Section 73.7, “Change configuration depending on the environment”
代碼的方式設置配置文件
您可以在應用程序運行之前通過調用SpringApplication.setAdditionalProfiles(…)
以編程方式設置活動配置文件。也可以使用Spring的ConfigurableEnvironment
接口激活配置文件。
特定文件的配置文件
加載文件時,會將application.properties
(或application.yml
)和通過@ConfigurationProperties
引用的文件的特定於配置文件的變體視爲文件。有關詳細信息,請參見第24.4節Section 24.4, “Profile-specific properties”。
日誌
Spring Boot 使用Commons Logging進行所有的內部日誌記錄.但是日誌的底層實現提供了Java Util Logging
,log4J2
,Logback
的默認配置.
默認情況下,如果您使用“啓動器”,則將使用Logback
進行日誌記錄。還包括適當的Logback
路由,以確保使用Java Util
日誌記錄,Commons Logging
,Log4J
或SLF4J
的從屬庫都能正常工作。
日誌格式
默認的日誌格式:
2014-03-05 10:57:51.112 INFO 45469 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.52
2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1358 ms
2014-03-05 10:57:51.698 INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2014-03-05 10:57:51.702 INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
日記將會輸出以下類型:
-
日期和時間 毫秒級精度,易於排序
-
日誌等級
ERROR
,WRAN
,INFO
,DEBUG
,TRACE
-
進程ID
-
分隔符
---
用於區分時間日誌消息的開始 -
線程名稱 用方括號括起來(對於控制檯輸出可能會被截斷)
-
記錄器名稱-通常是源類名稱(通常是縮寫)
-
日誌消息
Logback 沒有FATAL級別的日誌,它被歸納到ERROR日誌中
控制檯輸出
認日誌配置將在編寫消息時將消息回顯到控制檯。默認情況下,將記錄ERROR
,WARN
和INFO
級別的消息。您還可以通過使用--debug
標誌啓動應用程序來啓用“調試”模式。
$ java -jar myapp.jar --debug
你也可以使用application.properties
中配置debug=true
啓用調試模式後,將配置一些核心記錄器(嵌入式容器,Hibernate和Spring Boot)以輸出更多信息。啓用調試模式不會將您的應用程序配置爲記錄所有具有DEBUG級別的消息。
另外,您可以通過使用--trace
標誌(或application.properties
中的trace = true
)啓動應用程序來啓用“TRACE”模式。
日誌顏色
如果您的終端支持ANSI,則將使用彩色輸出來提高可讀性。您可以將spring.output.ansi.enabled
設置爲supported value,以覆蓋自動檢測。
使用%clr
轉換字配置顏色編碼。轉換器將以最簡單的形式根據對數級別爲輸出着色,例如:
%clr(%5p)
日誌級別對應的顏色:
Level | Color |
---|---|
| Red |
| Red |
| Yellow |
| Green |
| Green |
| Green |
另外,您可以通過將其提供爲轉換的選項來指定應使用的顏色或樣式。例如,將文本設爲黃色
%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}
支持以下顏色和樣式:
blue
cyan
faint
green
magenta
red
yellow
文件輸出日誌
默認情況下,Spring Boot將僅登錄到控制檯,並且不會寫入日誌文件。如果除了控制檯輸出外還想寫日誌文件,則需要設置logging.file
或logging.path
屬性(例如,在application.properties
中配置)。
logging.file | logging.path | Example | Description |
---|---|---|---|
(none) | (none) | Console only logging. | |
Specific file | (none) |
| Writes to the specified log file. Names can be an exact location or relative to the current directory. |
(none) | Specific directory |
| Writes |
日誌文件達到10 MB時將覆蓋,並且與控制檯輸出一樣,默認情況下會記錄ERROR
,WARN
和INFO
級別的消息。
日誌記錄系統在應用程序生命週期的早期進行了初始化,因此在通過@PropertySource批註加載的屬性文件中找不到此類日誌記錄屬性。
日誌記錄屬性獨立於實際的日誌記錄基礎結構。結果,特定的配置鍵(例如Logback的logback.configurationFile)不是由Spring Boot管理的。
日誌等級
日誌等級支持使用Spring 環境或者其他方式(application.properties
)來進行配置.loggin.level.*= {LEVEL}
,其中的{LEVEL}
可以使用TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF.
logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
默認情況下,Spring Boot重映射Thymeleaf
INFO
消息,以便它們以DEBUG
級別記錄。這有助於減少標準日誌輸出中的噪聲。有關如何在自己的配置中應用重新映射的詳細信息,請參見LevelRemappingAppender
自定義日誌配置
你可以通過類路徑來激活不同的日誌記錄系統,並通過根目錄中或者Spring Environment屬性的logging.config
指定適當的配置文件來自定義各種日誌記錄系統.
根據您的日誌記錄系統,將加載以下文件:
Logging System | Customization |
---|---|
Logback |
|
Log4j2 |
|
JDK (Java Util Logging) |
|
如果可能,我們建議您在日誌配置中使用-spring變體(例如logback-spring.xml
而不是logback.xml
)。如果使用標準配置位置,Spring將無法完全控制日誌初始化。
從“可執行jar”運行時,Java Util Logging
存在一些已知的類加載問題,這些問題會導致出現問題。我們建議您儘可能避免使用它。
爲了自定義,其他一些屬性從Spring Environment轉移到System屬性:
Spring Environment | System Property | Comments |
---|---|---|
|
| The conversion word that’s used when logging exceptions. |
|
| Used in default log configuration if defined. |
|
| Used in default log configuration if defined. |
|
| The log pattern to use on the console (stdout). (Only supported with the default logback setup.) |
|
| The log pattern to use in a file (if LOG_FILE enabled). (Only supported with the default logback setup.) |
|
| The format to use to render the log level (default |
|
| The current process ID (discovered if possible and when not already defined as an OS environment variable). |
Logback 拓展
pring Boot包含許多Logback擴展,可以幫助進行高級配置。您可以在logback-spring.xml
配置文件中使用這些擴展名。
您無法在標準logback.xml
配置文件中使用擴展名,因爲擴展名加載時間過早。您需要使用logback-spring.xml
或定義logging.config
屬性。
這些擴展不能與Logback的配置掃描一起使用。如果嘗試這樣做,則對配置文件進行更改將導致類似於以下記錄之一的錯誤:
ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]]
ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProfile], current ElementPath is [[configuration][springProfile]]
特殊的文件配置
<springProfile>
標籤允許您根據活動的Spring概要文件有選擇地包括或排除配置部分。在<configuration>
元素內的任何位置都支持概要文件部分。使用name屬性指定哪個配置文件接受配置。可以使用逗號分隔的列表指定多個配置文件。<springProfile name =“ staging”>
<springProfile name="staging">
<!-- configuration to be enabled when the "staging" profile is active -->
</springProfile>
<springProfile name="dev, staging">
<!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
</springProfile>
<springProfile name="!production">
<!-- configuration to be enabled when the "production" profile is not active -->
</springProfile>
環境特性
配合環境變量或者application.properties
使用
<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"
defaultValue="localhost"/>
<appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender">
<remoteHost>${fluentHost}</remoteHost>
...
</appender>
歡迎關注我的公衆號