preface

The last article to share, has led partners into the world of SpringBoot development. Let’s review it.

Last time I talked about the introduction of SpringBoot, convention is greater than configuration, environment construction and the creation of the first PC version of SpringBoot, so today I want to take you into the configuration of SpringBoot, to explore the configuration principle of SpringBoot, SpringBoot can also do this…

Chapter 2: SpringBoot Configuration

Key words: configuration file, loading sequence, configuration principle

1. Configuration files

SpringBoot uses a global configuration file with a fixed name;

application.properties

application.yml

The configuration file is used to: modify the default SpringBoot automatic configuration. SpringBoot is all configured for us at the bottom.

2. YAML syntax

2.1 Basic Syntax

K :(space)V: indicates a pair of impairment pairs (Spaces must be present);

Control hierarchy with space indented; It’s just a column of data that’s going to be left aligned, all at the same level.

server: port: 8081 path: /hello
Copy the code

2.2 Writing method of value

Literals: ordinary values (numbers, strings, booleans)

K: V: write it literally; Strings do not use single or double quotation marks by default. “” : double quotation marks; Does not escape special characters inside the string; Name: “zhangsan \n lisi” : output; Zhangsan linefeed lisi “: single quotation marks; The special characters are escaped, and the special characters are just a common string data name: ‘zhangsan \n lisi’ : output; zhangsan \n lisi

Object, Map (properties and values) (key-value pairs) : k:v: Writes the relationship between the properties and values of the object on the next line; Note that the indentation

The object is k: v again

friends:lastName: zhangsan age: 20
Copy the code

Written in line:

friends: {lastName: zhangsan,age: 18}
Copy the code

Array (List, Set)

Represents an element in an array with a – value

Pets: ‐ cat ‐ dog ‐ pigCopy the code

Inline writing

pets: [cat,dog,pig]
Copy the code

3. Loading sequence of external configuration

SpringBoot can also load configurations from the following locations; Priority from high to low; The configuration with a higher priority overrides the configuration with a lower priority, and all configurations form complementary configurations

3.1 Cli Parameters

All configurations can be specified on the command line

Java -jar spring-boot-02-config-02-0.0.1- snapshot. jar –server.port=8087 –server.context-path=/ ABC — Configuration item = value

2. JNDI properties from Java :comp/env

3.Java System Properties(system.getProperties ())

4. Operating system environment variables

5. RandomValuePropertySource configuration of the random. * attribute values

Search from outside jar package to inside JAR package;

Loading with profile is preferred

6. The application-{profile}. Properties or application

Application -{profile}. Properties or Application. Yml (with spring.profile) configuration file inside jar package

Then load without profile

Application. Properties or Application. Yml (without Spring.profile) configuration file outside the jar package

9. Application. Properties or Application. Yml (without Spring.profile) configuration file inside jar

10.@Configuration annotation @propertysource on the class

11. Through SpringApplication. SetDefaultProperties specify default properties

All supported configuration loading sources

Refer to official documentation

4. Principle of automatic configuration

What exactly can a configuration file write? How to write? Automatic configuration principle;

4.1 Principles of Automatic Configuration

1) When SpringBoot starts, the main configuration class is loaded and the automatic configuration function @enableAutoConfiguration is enabled

2) @eableAutoConfiguration

Using EnableAutoConfigurationImportSelector to import some components in the container.

You can view the contents of the selectImports() method;

List configurations = getCandidateConfigurations(annotationMetadata, attributes); Gets the candidate configuration

SpringFactoriesLoader. LoadFactoryNames () scans all the jar package classpath META ‐ INF/spring. The factories to scan to the contents of these files are packaged into a properties object Obtained from the properties to EnableAutoConfiguration. The class class (class name) corresponding values, then add them in the containerCopy the code

Add all the EnableAutoConfiguraion values configured in the meta-INF/Spring. factories under the classpath to the container.

# 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.cassandra.CassandraAutoConfiguration,\ org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\ org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\ org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\ org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\ org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration, \org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration ,\org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration ,\org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration  
Copy the code

Each xxxAuto is a component in the container, added to the container, and used for automatic configuration

3) Each automatic configuration class provides automatic configuration function

4), to the HttpEncodingAutoConfigration (Http code automatic configuration) as an example to explain the principle of automatic configuration

@configuration // Indicates that this is a Configuration class, just like the previous Configuration file, Can also add components to the container @ EnableConfigurationProperties (HttpEncodingProperties. Class) / / start the specified class ConfigurationProperties function; Bind the corresponding values in the configuration file to HttpEncodingProperties; And put HttpEncodingProperties join the ioc container @ ConditionalOnWebApplication / / Spring bottom @ Conditional annotations (Spring annotations), according to different conditions, if meet the specified conditions, The configuration of the entire configuration class takes effect; To determine whether the current application of web applications, if it is, the current effective configuration class @ ConditionalOnClass (CharacterEncodingFilter. Class) / / judge the current project have this class CharacterEncodingFilter; Filter for garble resolution in SpringMVC; @ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", MatchIfMissing = true) / / whether the configuration file is a configuration spring. HTTP. Encoding. Enabled; If there is no judgment is also set up / / even though we are in the configuration file is not configured pring. HTTP. Encoding. The enabled = true, is also the default effect; Public class HttpEncodingAutoConfiguration {/ / he has and SpringBoot configuration file mapping the private final HttpEncodingProperties properties; // If there is only one parameter constructor, The value of the parameter will be from the container take public HttpEncodingAutoConfiguration (HttpEncodingProperties properties) {enclosing the properties = properties; } @ Bean / / add a component to the container, the component of certain values need to obtain from the properties @ ConditionalOnMissingBean (CharacterEncodingFilter. Class) / / judge the container without this component? public CharacterEncodingFilter characterEncodingFilter() { CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter(); filter.setEncoding(this.properties.getCharset().name()); filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST)); filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE)); return filter; } @configurationProperties (prefix = "spring.http.encoding") // Bind the public class to the specified value and bean ownership from the configuration file HttpEncodingProperties {public static final Charset DEFAULT_CHARSET = charset.forname ("UTF‐8");Copy the code

Determine whether this configuration class takes effect based on the current conditions

Once the configuration class is in effect, it adds various components to the container whose properties are retrieved from the corresponding Properties class, each of which is bound to a configuration file.

5) All properties that can be configured in the configuration file are encapsulated in the xxxxProperties class. What can be configured in a configuration file to refer to the attribute class corresponding to a particular power

@configurationProperties (prefix = "spring.http.encoding") // Bind the public class to the specified value and bean ownership from the configuration file HttpEncodingProperties {public static final Charset DEFAULT_CHARSET = charset.forname ("UTF‐8");Copy the code

essence

1), SpringBoot boot will load a large number of configuration classes 2), let’s see if our program has SpringBoot to help us write automatic configuration classes by default

3) Let’s see what components are configured in this auto-configuration class.

When we add a component to the container auto-configuration class, we get some properties from the Properties class. We can specify the values of these properties in the configuration file

Afterword.

Understanding SpringBoot’s auto-configuration principles will make it easier for you to learn later. Of course, it is the essence of SpringBoot’s auto-configuration principles that can only be used in the “interview” process, but if you have a thorough understanding of SpringBoot auto-configuration principles in the workplace, Nothing will go wrong.