From 0-1 in-depth understanding SpringBoot features (version 2.X) - fifth day

Disclaimer: if reproduced - please add the next micro-channel can inform 457,556,886 knowledge is shared https://blog.csdn.net/wolf_love666/article/details/90514437

First, the configuration file

spring configuration file may be split so that the profile is only available in certain example by an environment. Any @Component or @Configuration be modified @Profile will be limited at load time, as in the following example:

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

	// ...

}

If the codes do not want intrusive, can then use the configuration file or command line

配置文件中
spring.profiles.active=dev,hsqldb
命令行模式
--spring.profiles.active=dev,hsqldb

1.1) is added to activate the configuration file
can later be designated by the above said, if I how to specify multiple configuration files can be together this way: Suppose prod specified time, proddb, prodmq also be activated

---
my.property: fromyamlfile
---
spring.profiles: prod
spring.profiles.include:
  - proddb
  - prodmq

Other changes in the environment configuration can refer to this article

1.2) set up a profile programmatically, but before you must start the application run

SpringApplication.setAdditionalProfiles(…​)
然后通过ConfigurableEnvironment接口激活文件

1.3) specify a particular profile can refer to the articleHere Insert Picture Description

Second, log

Spring Boot generic logging of all internal log, but keep the underlying logging implementation. For the Java Util Logging, Log4J2 and Logback provide a default configuration. In each case, the logger is pre-configured to use the console output, and also provides an optional output file.
By default, if you use a starter, log default is Logback. However, you can change the routing policy to select other java logging tools, Commons Logging, Log4J, or SLF4J .
For java, it logs a lot of open-source framework, so do not worry about the above framework, in general, do not have to rely on a change log, SpringBoot also work well.

2.1) log format
default output log log logback follows:
log level ERROR, WARN, INFO, DEBUG, or TRACE no FATAL, ERROR is an alternative level.
Log output as follows:
Here Insert Picture Description

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: [/*]

2.2) output console
default is INFO level and above, but you can turn on debug debug mode

java -jar myapp.jar --debug/--trace

If the configuration file is specified, then debug = true / trace = true in application.properties

2.2.1) color code output
if your terminal supports ANSI, color output to help readability. You can set the subject to enable spring.output.ansi.enabled supported values to cover the automatic detection of
color-coded by using the conversion words% clr configuration. In the simplest form, the output of the converter to be colored according to the log level, as shown in the following example

%clr(%5p)

The default color output
Here Insert Picture Description
can specify the color output
Here Insert Picture Description

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

2.3) file output
by default SpringBoot only the log output to the console, do not write the log file, if you want the extra log output to a log file, you can set logging.file or logging.path properties in the configuration file application.properties .
Supported log log attribute table is as follows:

logging.file logging.path example description
no no no Only output to the console
Specified file no my.log Written to the specified file can be relative path absolute path also can be the current directory
no Specified directory / Var / log Spring.log write to the specified directory, can be an absolute path, or a relative path to the current directory

The default log output file size is 10MB, if you want to change the log file size can not be changed by setting the previous logging.file.max-size property, unless also set logging.file.max-history attributes.
It is worth noting:
the log system initialized early in the application lifecycle. Therefore, the log can not find the property in the properties file loaded in the comment by @PropertySource.
Log properties independent of the actual logging infrastructure. Thus, a specific configuration keys (e.g. logback). Not by the spring Boot management.

2.4) log level
all supported TRACE, DEBUG, INFO, WARN, ERROR, FATAL, or OFF log level can be specified by the following command:

logging.level.<logger-name>=<level>

logging.level.root root root logs can be configured as follows

logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR

2.5) log group
logging program can be related grouped together, to be able to configure them simultaneously, it is often useful, such as in the tomcat tomcat, external calls in external call. For example, assume that change all the log level logger associated with Tomcat, but can not control the root package.
So in order to solve this problem, SpringBoot allows you to define log grouped in spring environment. For Liezi, a top tomcat log packet. Thus org.apache.catalina, org.apache.coyote, org.apache.tomcat log packet in the root package tomcat under management.

logging.group.tomcat=org.apache.catalina, org.apache.coyote, org.apache.tomcat

Once you have defined it above the log group, you can easily control the logging group level

logging.level.tomcat=TRACE

Spring Boot log group comprising predefined, out of the box

name Log Output
web org.springframework.core.codec, org.springframework.http, org.springframework.web
sql org.springframework.jdbc.core, org.hibernate.SQL

2.6) customized log configuration
Since the default is logback logging framework, but assuming you are using the original project migration frameworks such as log4j, this time on the need to configure a custom log. You can configure the amount logging.config environmental properties of the spring. You can also use org.springframework.boot.logging.LoggingSystem forced through a particular log system. This value should be a fully qualified class name LoggingSystem achieved. You can also use the value none completely disable the Spring Boot logging configuration

Because the log is initialized before the application context is created, he can not be in the spring configuration files or modified files @PropertySources @Configuration control system or its change log The only way to completely disable the system through the property.

Depending on your log system, these files will be loaded
Here Insert Picture Description
if possible, we recommend that you use -spring variants (eg, logback-spring.xml instead logback.xml) in the log configuration. If you use the standard configuration location, Spring can not fully control log initialization
There are some known problems class loading Java Util Logging, these problems will cause problems from "executable jar" runtime. If possible, avoid the use of official recommendations from the "executable jar" when it runs
in the adaptation of time, as some properties will change the conversion:

spring environment System Properties Explanation
logging.exception-conversion-word LOG_EXCEPTION_CONVERSION_WORD Recording the converted words used abnormal
logging.file LOG_FILE If you have defined, use the default log configuration
logging.file.max-size LOG_FILE_MAX_SIZE The maximum log file size (if enabled LOG_FILE). (Logback supports only the default settings.)
logging.file.max-history LOG_FILE_MAX_HISTORY The maximum number of archive log files to keep (if enabled LOG_FILE). (Logback supports only the default settings.)
logging.path LOG_PATH If you have defined, use the default log configuration
logging.pattern.console CONSOLE_LOG_PATTERN To log mode used in the console (stdout) on. (Logback supports only the default settings.)
logging.pattern.dateformat LOG_DATEFORMAT_PATTERN Additional mode log date format. (Logback supports only the default settings.)
logging.pattern.file FILE_LOG_PATTERN To log mode (if enabled LOG_FILE) used in the file. (Logback supports only the default settings.)
logging.pattern.level LOG_LEVEL_PATTERN The format used when rendering the logging level (default% 5p). (Logback supports only the default settings.)
PID PID The current process ID (if possible, not yet defined as found in the OS environment variables).

== all logging system supported when parsing the configuration file can reference system properties. SpringBoot the jar default configuration
Here Insert Picture Description
if you want the log properties placeholder Spring Boot should use the syntax of the frame and not the underlying syntax. It is noteworthy that, if Logback, should be used: as a separator between property name and its default value, instead of using: -.
You can cover only LOG_LEVEL_PATTERN (or logging.pattern), and other special MDC added to the contents of the log line. And Logback level). For example, if you use a log .pattern. level = user:% X {user }% 5p, then the default log format includes "user" of MDC entry (if present), as shown in the example below.
Here Insert Picture Description
2.7) Logback extended
Spring Boot Logback includes many extensions that can help with advanced configuration. You can use these extensions in your logback-spring.xml profile
because the standard log .xml configuration file is loaded too early, it can not be used therein extension. You need to use logback-spring.xml or custom logging. Configuration attributes
these extensions can not be Logback the configuration scanning used together. If you try to do so, to make changes to the configuration file will result in an error that resembles one of the following Error

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]]

2.7.1) special profile configuration

<springProfile>标记允许您根据活动的Spring配置文件选择性地包含或排除配置部分。
概要文件部分在<configuration>元素的任何位置都受支持。使用name属性指定哪个配置文件接受配置。
<springProfile>标记可以包含一个简单的概要文件名称(例如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>

2.7.2) environment attributes

<springProperty>标记允许您公开Spring环境中的属性,以便在Logback中使用。如果希望从应用程序访问值,那么这样做非常有用。
返回配置中的属性文件。标签的工作方式与Logback的标准<property>标签类似。
但是,您不是指定一个直接值,而是指定属性的源(来自环境)。如果需要将属性存储在本地范围之外的其他地方,可以使用scope属性。
如果需要回退值(如果该属性没有在环境中设置),可以使用defaultValue属性。下面的示例显示如何公开属性以便在Logback中使用。
<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>

Source file must be specified (e.g. my.property-name) in the kebab. However, you can use the relaxed rules will attribute to the environment

Third, international

Spring Boot support localized messages, so your application in different languages to meet user preferences. By default, Spring Boot resource lookup message packet exists in the root directory of the classpath
when configured default resource bundle properties file is available (i.e. message), the application will be automatically configured. Attribute by default). If the resource package contains only the language-specific properties files, you need to add a default value
can be used to configure resource bundles basename spring and several other properties. Namespace message, as shown in the following example

spring.messages.basename=messages,config.i18n.messages
spring.messages.fallback-to-system-locale=false

spring.messages.basename comma-separated list of supported positions, including a resource package qualifiers or parsed from the root class path, more references

Four, JSON

SpringBoot integrated by default are several, but the default is Jackson
Here Insert Picture Description
4.1) Jackson
provides automatic configuration of Jackson, Jackson is part of the spring-boot-starter-json in. When Jackson on the classpath, will automatically configure ObjectMapper bean. Provides several configuration properties to customize ObjectMapper configuration
4.2) Gson
provides Gson automatic configuration. When Gson on the classpath, will automatically configure Gson bean. Several spring.gson. * Configuration properties for the custom configuration. For more control, you may use one or more instances GsonBuilderCustomizer bean.
4.3) JSON-B
provides automatic configuration of JSON-B. When implemented JSON-B API and on the classpath, will automatically configure Jsonb bean. JSON-B preferred implementation is Apache Johnzon, which provides dependency management

Guess you like

Origin blog.csdn.net/wolf_love666/article/details/90514437