1. Configuration file

Spring Boot uses a global configuration file with a fixed name. The following two types of configuration files can be loaded by Spring Boot

  • application.properties
  • application.yml

What the configuration file does: Change the default value of Spring Boot automatic configuration. Spring Boot will load the configuration file and automatically configure it for us.

Configuration files are typically placed in the SRC /main/resources directory or under the classpath /config

2. The YAML

2.1 introduction of YAML

YAML: YAML Ain’t Markup Language, there is Another explanation Yet Another Markup Language”. YAML, as a markup language, is used to write configuration files. YAML is different from the configuration files written in XXX.xml. YAML is data-oriented and is more suitable for configuration files such as XXX.yml or XXX.yaml.

Contrast YAML with XML writing configuration

YAML writing

server:
  port: 8081
Copy the code

XML writing

<server>
    <prot>8081</prot>
</server>
Copy the code

YAML advantages:

  • YAML is easy for people to read.
  • YAML data is portable between programming languages.
  • YAML matches the native data structures of agile languages.
  • YAML has a consistent model to support common tools.
  • YAML supports one-way processing.
  • YAML is expressive and extensible.
  • YAML is easy to implement and use.

2.2 YAML syntax

2.2.1 Basic Syntax

Basic writing: K:(space)V denotes a key-value pair (note Spaces)

  • Use indentation to indicate hierarchy
  • Only Spaces can be used for indentation, not tabs
  • The number of Spaces indented does not matter, as long as elements of the same level are left aligned
  • Case sensitivity
  • Loosely expressed, in Java for camel nomenclature, you can use the original name or use – instead of camel. Such as the lastName attribute in Java, using lastName or last-name in YML will map correctly.

2.2.2 Writing method of value

Literals: ordinary values (numbers, strings, booleans)

Write k: v directly, note the space.

Strings can be written in multiple lines, starting with the second line, and must have a single space indent. Newline characters are converted to Spaces

By default, single or double quotation marks are not required for strings. Quotation marks have different meanings.

  • “” Double quotes: Special characters in a string are not escaped. Special characters represent the original meaning.

    Example: name: “zhangsan \\ wangwu” output: zhangsan \ lisi

  • “Single quotes: Escape special characters in a string. A special character is ultimately just plain string data.

    Example: name: ‘zhangsan \ lisi’ output: zhangsan \ lisi

Code examples:

name: zhangsan
age: 12
birthday: 2020/ 10/14
Copy the code

② Objects, Maps (attributes and values) (key-value pairs)

  • Object, delimited by:. Colon followed by space to separate key values;

  • The next line begins with the properties and values, indent to the left;

  • You can also write it on the same line, with the attribute wrapped in {}, with the attribute split;

Code examples:

person:
  name: lisi
  age: 23
  sex: male
  birthday: 2020/ 10/12
dog:
  name: huahua
  age: 2
Copy the code

Written in line:

person: {name: lisi.age: 23.sex: flmale.birthday: 2020/ 10/12}. dog: {name: huahua.age: 2}
Copy the code

Array (List, Set)

Use – to represent an element in an array. A group of lines starting with – forms an array.

Inline writing can also be used, inline writing is wrapped with [];

Code examples:

list:
-aaa
-bbb
-ccc
Copy the code

Inline writing

list:[aaa, bbb, ccc]
Copy the code

(4) document

Multiple documents are separated by –

Code examples:

server:
  port: 8081
spring:
  profiles:
    active: prod

---
server:
  port: 8083
spring:
  profiles: dev

---
server:
  port:8084
spring:
  profiles: prod
Copy the code

YAML syntax check test address: YAML syntax check

3. Configure file value injection

3.1 Attribute Injection

Either way, the @Value annotation and the @ConfigurationProperties annotation get the Value from the configuration file.

ConfigurationProperties: tells SpringBoot to bind all properties in this class to the relevant configuration in the configuration file.

@value: Inject a Value into the property;

Compare the two ways to get values

@ConfigurationProperties @Value
function Batch injection of properties in the configuration file A single specified
Loose binding (loose syntax) support Does not support
SpEL Does not support support
JSR303 data verification support Does not support
Complex type encapsulation support Does not support

Both yML and Properties are available in configuration files;

@value is used when a business logic simply needs to fetch a Value from a configuration file.

Use @ConfigurationProperties when we write a javaBean to map to a configuration file and need to batch inject properties

Verify the javabean configuration file injection data using the @valiadated annotation:

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {

// @Value("${person.last-name}")
    @email (message = "mailbox authentication failed ")
    private String lastName;

// @Value("#{11*2}")
    private Integer age;
    private Boolean boss;

    private Date birthday;
    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;

    private Map<String, Object> mapsInline;
    private List<Object> listsInline;
}
Copy the code

The use of the @validatede annotation is not covered here, but will be covered in more detail in a future blog post.

3.2 Loading a Configuration File

The @propertysource and @importResource annotations can be used to load configuration files.

① @propertysource: Loads the specified configuration file.

/** * maps the value of each property configured in the configuration file to this component *@ConfigurationProperties: tells SpringBoot to bind all properties in this class to the relevant configuration in the configuration file; * prefix = "person" : map all attributes under person in the configuration file to attributes in the class * * The component can only be provided by the container if it is a component in the container@ConfigurationPropertiesFunction; *@ConfigurationProperties(prefix = "person") gets the value from the global configuration file by default; * * /
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {

// @Value("${person.last-name}")
// @email (message = "mailbox authentication failed ")
    private String lastName;

// @Value("#{11*2}")
    private Integer age;
    private Boolean boss;

    private Date birthday;
    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;

    private Map<String, Object> mapsInline;
    private List<Object> listsInline;
}
Copy the code

② @importResource: Import the Spring configuration file to make the content in the Spring configuration file take effect.

  • There is no Spring configuration file in the Spring Boot project, and the Spring configuration file we wrote will not be loaded by default;
  • If you want the Spring configuration file to take effect, use@ImportSourceAnnotations, annotated on the main startup class;

External Spring configuration file beans.xml


      
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="hello" class="cn.bruce.springboot.service.HelloService"></bean>
    <bean id="test" class="cn.bruce.springboot.service.TestService"/>
</beans>
Copy the code

The main boot class, SpringBootApplication

@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringbootApplication {

	public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); }}Copy the code

Spring does not recommend importing external Spring configuration files. It is recommended to use configuration classes for Spring configuration, i.e. fully annotated configuration

@configuration: Indicates that the current class is a Configuration class. Used to replace the previous Spring configuration file

@Configuration
public class MyAppConfig {
	/ * * *@BeanEquivalent to the <bean><bean/> tag in the configuration file, which is used to inject components */
    @Bean
    public HelloService helloService(a) {
        System.out.println("Configure class @bean to add components to container...");
        return newHelloService(); }}Copy the code

3.3 Configuration File placeholders

You can use the file placeholder ${XXXX} in the configuration file to use random numbers or reference properties or you can set the default value

3.3.1 random number

You can use the following placeholders to generate random numbers, and you can also specify random number types

${random. Uuid} : Generates a RANDOM UUID

${random.value} : generates a random string

${random. Int} : generates a random int number

${random.int(value,[Max])} Generates a random number and specifies the maximum value

${random.long} : Generates log numbers randomly

${random. Long (value,[Max])} : Generates a random long number, the maximum value can be specified

3.3.2 Attribute placeholders

  • You can reference previously configured properties in the configuration file;
  • use:To specify the default value;

Code examples:

person.last-name=Zhang SAN ${random. Value}
person.age=${random.int(100)}
person.birthday=2020/10/11
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.last-name} have a dog
person.dog.age=${initAge:12}
Copy the code

4. About the Profile

Profile is Spring’s support for providing different configuration functions for different environments. You can quickly switch environments by activating and specifying parameters.

4.1 Multiple Profile files

When writing the main profile, the file name can be application-{profile}.properties/ yML. For example, application-dev.properties and application-prod.properties

The default configuration in application.properties is used; Activates the specified profile in the application.properties file

4.2 Multiple Profile Document blocks

In YAML, you can use different document blocks to configure different profiles and activate the specified profile in the default configuration

# default configuration
server:
  port: 8081
spring:
  profiles:
    active: dev

---
# Development environment
server:
  port: 8083
spring:
  profiles: dev

---
# Production environment
server:
  port: 8084
spring:
  profiles: prod
Copy the code

4.3 Activating a Profile

(1) in the application configuration file. The properties/yml specified in the spring. The profiles. The active = {profile}}

② On the command line, the configuration command –spring.profiles.active={profile}} adds the configuration command when running the built JAR package

③ Add the VM parameter -dspring.profiles. active=dev

Configure command line parameters and VM parameters in the IDE. The following uses IDEA as an example:

Note: {profile} indicates the environment name, such as dev, prod, etc

5. Load the configuration file

5.1 Configuration File Loading Position

Spring Boot scans the application.properties and application.yml files in the following locations as the default configuration files for Spring Boot.

  • file:./config/: in the config folder of the project
  • file:./: in the project file
  • classpath:/config/: SRC /resource/config folder
  • classpath:/: SRC /resource folder

The loading priorities are in descending order. The configuration with a higher priority overrides the configuration with a lower priority.

Spring Boot loads all configuration files for these four locations to form complementary configurations.

You can change the default configuration file location via spring.config.location;

You can specify the new location of the configuration file when starting the project using command-line arguments. Specified profiles and default loaded profiles work together to form complementary configurations; You can use the CLI to adjust the configuration information for o&M.

Command line parameters: – spring. Config. Location = G: / application properties

Such as at deployment time to perform this command: Java jar – spring – the boot – 02 – config – 02-0.0.1 – the SNAPSHOT. Jar — spring. Config. Location = E:. / application properties

5.2 Loading Sequence of External Configuration Files

Spring Boot supports a variety of configuration methods, including loading information not only inside the project, but also external configuration information. Spring Boot loads information for the following locations, in descending order of priority. The configuration with a higher priority overrides the configuration with a lower priority, and all configurations form complementary configurations.

① Command line parameters. All configurations can be specified on the command line

For example, java-jar spring-boot-02-config-02-0.0.1- snapshot. jar –server.port=8087 –server.context-path=/ ABC

② JNDI attributes from Java :comp/env;

System.getproperties ();

④ Operating system environment;

(5) RandomValuePropertySource configuration of the random. * attribute value;

Application -{profile}. Properties or application. Yml (with spring.

Application -{profile}. Properties or application. Yml (with spring.

Application. Properties or Application. Yml (without spring.

⑨ jar application. Properties or Application. Yml (without spring.profile) configuration file;

⑩ @configuration @propertysource on the annotation class;

Through SpringApplication. SetDefaultProperties specified default attributes;

Spring Boot official documentation: Spring Boot loading sequence

Summary: The sequence of loading configuration files inside and outside the JAR package is searched from inside and outside the JAR package. The configuration file with {profile} is loaded first, and the configuration file without {profile} is loaded later. That is, jar packages are configured from the outside to the inside, from those with {profile} to those without {profile}

6. Principle of automatic configuration

The Spring Boot configuration file can write what content, and write rules are determined by its automatic configuration principle, so understand the Spring Boot automatic configuration principle also master the content of the Spring Boot configuration file.

6.1 Mechanism of Automatic Configuration

SpringBoot loads the main configuration class at startup. The main configuration class contains the @SpringBootApplication annotation, which is a composite annotation. The annotation @enableAutoConfiguration is used to enable the automatic configuration function of Spring Boot. The following describes the composition and functions of the annotation.

The @enableAutoConfiguration annotation is used to prompt Spring Boot to enable automatic configuration and load configuration information. The configuration information consists of Spring Boot automatic configuration information and the configuration file information written by us.

6.1.1 @EnableAutoConfigurationAnnotating the process for loading the auto-configuration class:

@enableAutoConfiguration Annotated source code

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

    /** * Specifies the configuration item */ in the configuration file
	String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 * @return the classes to exclude
	 */Class<? >[] exclude()default {};

	/**
	 * Exclude specific auto-configuration class names such that they will never be
	 * applied.
	 * @return the class names to exclude
	 * @since1.3.0 * /
	String[] excludeName() default {};

}
Copy the code

The @enableAutoConfiguration annotation consists of the @AutoConfigurationPackage and the @import annotation.

  • @autoConfigurationPackage Annotations: Automatically configurationPackage annotations

  • @import annotation: Is a Spring low-level annotation used to inject a component into a container.

  • @ Import (AutoConfigurationImportSelector. Class) : Import AutoConfigurationImportSelector class configuration of automatic configuration information.

1) AutoConfigurationImportSelector class implements the ImportSelector selectImport methods of interface, is used to select the imported automatic configuration; And selectImport method call getAutoConfigurationEntry method;

@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
    if(! isEnabled(annotationMetadata)) {return NO_IMPORTS;
    }
    AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(annotationMetadata);// Call this method to load the configuration information
    return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
Copy the code

(2) getAutoConfigurationEntry method call getCandidateConfigurations method;

protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
    if(! isEnabled(annotationMetadata)) {return EMPTY_ENTRY;
    }
    AnnotationAttributes attributes = getAttributes(annotationMetadata);
    List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
    configurations = removeDuplicates(configurations);
    Set<String> exclusions = getExclusions(annotationMetadata, attributes);
    checkExcludedClasses(configurations, exclusions);
    configurations.removeAll(exclusions);
    configurations = getConfigurationClassFilter().filter(configurations);
    fireAutoConfigurationImportEvents(configurations, exclusions);
    return new AutoConfigurationEntry(configurations, exclusions);
}
Copy the code

(3) getCandidateConfigurations method called SpringFactoriesLoader loadFactoryNames method in class

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
                                                                         getBeanClassLoader());
    Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
                    + "are using a custom packaging, make sure that file is correct.");
    return configurations;
}
Copy the code

Call loadFactoryNames method when the incoming getSpringFactoriesLoaderFactoryClass () as a parameter, the method returns EnableAutoConfiguration annotations, Load the default configuration file information specified in the EnableAutoConfiguration annotation.

protectedClass<? > getSpringFactoriesLoaderFactoryClass() {return EnableAutoConfiguration.class;
}
Copy the code

The SpringFactoriesLoader class contains methods to load external configuration file information

public final class SpringFactoriesLoader {

	/** * The location to look for factories. * 

Can be present in multiple JAR files. * The META-INF/spring.factories path lets you get the values specified by EnableAutoConfiguration and import them into the container as auto-configuration classes

public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories"; private static final Log logger = LogFactory.getLog(SpringFactoriesLoader.class); private static final Map<ClassLoader, MultiValueMap<String, String>> cache = new ConcurrentReferenceHashMap<>(); private SpringFactoriesLoader(a) {}/** * Load and instantiate the factory implementations of the given type from * {@value #FACTORIES_RESOURCE_LOCATION}, using the given class loader. * <p>The returned factories are sorted through {@link AnnotationAwareOrderComparator}. * <p>If a custom instantiation strategy is required, use {@link #loadFactoryNames} * to obtain all registered factory names. * @param factoryType the interface or abstract class representing the factory * @param classLoader the ClassLoader to use for loading (can be {@code null} to use the default) * @throws IllegalArgumentException if any factory implementation class cannot * be loaded or if an error occurs while instantiating any factory * @see #loadFactoryNames */ public static <T> List<T> loadFactories(Class<T> factoryType, @Nullable ClassLoader classLoader) { Assert.notNull(factoryType, "'factoryType' must not be null"); ClassLoader classLoaderToUse = classLoader; if (classLoaderToUse == null) { classLoaderToUse = SpringFactoriesLoader.class.getClassLoader(); } List<String> factoryImplementationNames = loadFactoryNames(factoryType, classLoaderToUse); if (logger.isTraceEnabled()) { logger.trace("Loaded [" + factoryType.getName() + "] names: " + factoryImplementationNames); } List<T> result = new ArrayList<>(factoryImplementationNames.size()); for (String factoryImplementationName : factoryImplementationNames) { result.add(instantiateFactory(factoryImplementationName, factoryType, classLoaderToUse)); } AnnotationAwareOrderComparator.sort(result); return result; } /** * Load the fully qualified class names of factory implementations of the * given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given * class loader. * @param factoryType the interface or abstract class representing the factory * @param classLoader the ClassLoader to use for loading resources; can be * {@code null} to use the default * @throws IllegalArgumentException if an error occurs while loading factory names * @see #loadFactories */ public static List<String> loadFactoryNames(Class<? > factoryType,@Nullable ClassLoader classLoader) { String factoryTypeName = factoryType.getName(); return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList()); } /** * is the method that performs the final action in the process. This method loads the external configuration file using the class loader, reads the configuration from the configuration file and uses the LinkedHashMap as the storage structure, and finally returns the information to the configuration information. * * / private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) { MultiValueMap<String, String> result = cache.get(classLoader); if(result ! =null) { return result; } try{ Enumeration<URL> urls = (classLoader ! =null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) : ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION)); result = new LinkedMultiValueMap<>(); while (urls.hasMoreElements()) { URL url = urls.nextElement(); UrlResource resource = new UrlResource(url); Properties properties = PropertiesLoaderUtils.loadProperties(resource); for(Map.Entry<? ,? > entry : properties.entrySet()) { String factoryTypeName = ((String) entry.getKey()).trim();for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) { result.add(factoryTypeName, factoryImplementationName.trim()); } } } cache.put(classLoader, result); return result; } catch (IOException ex) { throw new IllegalArgumentException("Unable to load factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex); }}@SuppressWarnings("unchecked") private static <T> T instantiateFactory(String factoryImplementationName, Class<T> factoryType, ClassLoader classLoader) { try{ Class<? > factoryImplementationClass = ClassUtils.forName(factoryImplementationName, classLoader);if(! factoryType.isAssignableFrom(factoryImplementationClass)) {throw new IllegalArgumentException( "Class [" + factoryImplementationName + "] is not assignable to factory type [" + factoryType.getName() + "]"); } return (T) ReflectionUtils.accessibleConstructor(factoryImplementationClass).newInstance(); } catch (Throwable ex) { throw new IllegalArgumentException( "Unable to instantiate factory class [" + factoryImplementationName + "] for factory type [" + factoryType.getName() + "]", ex); }}}Copy the code

loadSpringFactoriesMain functions of the method:

  • Scan all JAR packages in the classpathMETA ‐ INF/spring. Factories;
  • Wrap the contents of these scanned files as properties objects;
  • Obtained from propertiesEnableAutoConfiguration.classClass, and add them to the container;

After a series of method calls, Spring Boot finally gets the information about the auto-configuration classes in the configuration file. Through @ Import annotations to AutoConfigurationImportSelector loading to the IoC container, by calling the interface ImportSelector selectImports method, can get configuration information in the configuration file, The Spring Boot automatic configuration is complete.

The Spring Boot autoconfiguration file is specified by the SpringFactoriesLoader class for the path and file. The @enableAutoConfiguration annotation specifies the value of the configuration in the configuration file, which ultimately points to the auto-configuration information.

Spring-boot-autoconfigure-2.3.4.release.jar! \ meta-INF \spring.factories The following configuration information is the spring Boot auto-configured class.

# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\ org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\ org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\ org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\ org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\ ....... , \... , \... ,\ org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\ org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\ org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfigurationCopy the code

Each such xxxAutoConfiguration class is a component in the container and is loaded into the container. Spring Boot uses these configuration classes to do automatic configuration; Each auto-configuration class completes the auto-configuration of some function.

6.1.2 Automatic Configuration Principle of Class loading Configuration

The auto-configuration class completes the configuration of related functions, and this is the last step of auto-configuration

With HttpEncodingAutoConfiguration (Http code automatically configure class) as an example explain the configuration principle of automatic configuration.

Automatic configuration class: HttpEncodingAutoConfiguration

@Configuration(proxyBeanMethods = false)// Specify that this class is a configuration class that can inject components into the container
@EnableConfigurationProperties(ServerProperties.class)// Enable ConfigurationProperties for the specified class; Bind the corresponding values in the configuration file to ServerProperties; Add ServerProperties to the IoC container
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)// Check whether the current application is a Web application. If yes, the configuration takes effect.
/ / ConditionOnXXX annotations are Spring annotations @ Conditional notes at the bottom of the extension, configure the configuration to take effect if the specified conditions, the entire configuration will not take effect.
@ConditionalOnClass(CharacterEncodingFilter.class)// Check whether the current project has the CharacterEncodingFilter class. This class is SpringMVC's filter to resolve the garble problem
@ConditionalOnProperty(prefix = "server.servlet.encoding", value = "enabled", matchIfMissing = true) Server.servlet.encoding; // Check whether a configuration exists in the configuration file. That is, whether our configuration file is configured with server.servlet.encoding; This configuration takes effect by default if no configuration is configured.
public class HttpEncodingAutoConfiguration {

    // Map to the SpringBoot configuration file
	private final Encoding properties;

    // In the case of only one parameter constructor, the parameter values are taken from the container
	public HttpEncodingAutoConfiguration(ServerProperties properties) {
		this.properties = properties.getServlet().getEncoding();
	}

	@Bean // Add a component to the container with parameter values from properties
	@ConditionalOnMissingBean
	public CharacterEncodingFilter characterEncodingFilter(a) {
		CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
		filter.setEncoding(this.properties.getCharset().name());
		filter.setForceRequestEncoding(this.properties.shouldForce(Encoding.Type.REQUEST));
		filter.setForceResponseEncoding(this.properties.shouldForce(Encoding.Type.RESPONSE));
		return filter;
	}

	@Bean
	public LocaleCharsetMappingsCustomizer localeCharsetMappingsCustomizer(a) {
		return new LocaleCharsetMappingsCustomizer(this.properties);
	}

	static class LocaleCharsetMappingsCustomizer
			implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered {

		private final Encoding properties;

		LocaleCharsetMappingsCustomizer(Encoding properties) {
			this.properties = properties;
		}

		@Override
		public void customize(ConfigurableServletWebServerFactory factory) {
			if (this.properties.getMapping() ! =null) {
				factory.setLocaleCharsetMappings(this.properties.getMapping()); }}@Override
		public int getOrder(a) {
			return 0; }}}Copy the code

All properties that can be configured in a configuration file are encapsulated in the xxxProperties property class; The configuration file can be configured to refer to the properties class of an auto-configuration class. Such as the configuration properties in the configuration class HttpEncodingAutoConfiguration ServerProperties

Automatic configuration property class: ServceProperties

@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)// // takes the specified value from the configuration file and binds it to the bean's properties
public class ServerProperties {
 
    // Set the default encoding of the URI to UTF-8, which can also be specified in the configuration file
    privateCharset uriEncoding = StandardCharsets.UTF_8; . }Copy the code

ConditionOnXXX is an extension of Spring’s underlying @Conditionality annotation. ConditionOnXXX is used to determine whether the current configuration class meets certain conditions, and if so, the configuration class takes effect. The configuration class, if in effect, injects components into the IoC container whose properties are obtained from the corresponding xxxProperties class, each of which corresponds to a configuration item in the configuration file.

About the various classes and notes:

  • @ConditionOnXXX: Determines whether the current configuration class meets the conditions.
  • xxxAutoConfiguration: automatic configuration class; Use to inject components into a container
  • xxxProperties: Attribute class corresponding to the auto-configuration class; Encapsulate the related properties in the configuration file
  • yml/properties: Configuration items in the file correspond to values in the attribute class;

Spring Boot Automatic configuration summary:

Spring Boot contains a large number of automatic configuration class xxxAutoConfiguration;

Spring Boot loads automatic configuration classes when it is started.

③ When the constraints in the configuration class are met, the automatic configuration class will be loaded into the IoC container;

④ The configuration properties class xxxProperties in the automatic configuration class is configured with configurable properties.

⑤ Spring Boot will map the attributes in the configuration attribute class to the data items in the configuration file;

Lessons for using Spring Boot:

Spring Boot loads a lot of automatic configuration when it starts up.

② In the use of Spring Boot we can view the functions we need Spring Boot has the relevant automatic configuration class;

③ If yes, check which components are configured in this automatic configuration class. (If the component we want is already loaded, no configuration is required.)

(4) When adding components to the container, some properties will be loaded from the automatically configured properties class. You can specify the values of these properties in the configuration file.

6.2 @ConditionalThe derived annotations

ConditionOnXXX is a Conditional annotation derived from the @Conditional annotation. ConditionOnXXX is used to determine whether certain conditions are met by the current configuration class. If so, the configuration class takes effect.

Action: Only if the conditions specified in the @Conditional derived annotation are true, components are added to the container, and all contents in the configuration class take effect;

@ConditionalThe derived annotations Function (Determine whether specified conditions are met)
@ConditionalOnJava Check whether the Java version of the system meets requirements
@ConditionalOnBean The specified Bean exists in the container
@ConditionalOnMissingBean There is no specified Bean in the container
@ConditionalOnExpression Satisfies the SpEL expression specification
@ConditionalOnClass There are specified classes in the system
@ConditionalOnMissingClass There is no specified class in the system
@ConditionalOnSingleCandidate There is only one specified Bean in the container, or the Bean is the preferred Bean
@ConditionalOnProperty Whether a specified property in the system has a specified value
@ConditionalOnResource Whether the specified resource file exists in the classpath
@ConditionalOnWebApplication The current environment is web
@ConditionalOnNotWebApplication The current environment is not Web
@ConditionalOnJndi JNDI has the specified entry

Automatic configuration classes take effect only under certain conditions. You can enable the debug attribute debug=true in the configuration file to view the configuration classes loaded by Spring Boot. In this way, you do not need to check the loading conditions of each automatic configuration class one by one.

Information printed by the console

= = = = = = = = = = = = = = = = = = = = = = = = = = = = the CONDITIONS EVALUATION REPORT = = = = = = = = = = = = = = = = = = = = = = = = = = = = Positive matches: / / load automatic configuration classes ----------------- AopAutoConfiguration matched: - @ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition) AopAutoConfiguration.ClassProxyingConfiguration matched: - @ConditionalOnMissingClass did not find unwanted class 'org.aspectj.weaver.Advice' (OnClassCondition) - @ConditionalOnProperty (spring.aop.proxy-target-class=true) matched (OnPropertyCondition) ...... Negative matches: / / not loaded automatic configuration class -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ActiveMQAutoConfiguration: Did not match: / / not the cause of the load - @ ConditionalOnClass Did not find the required class 'javax.jms. ConnectionFactory' (OnClassCondition) ......Copy the code