Alt+Ins: Quickly call up getter, setter, or toString methods.

Configuration file

1. Configuration files

  • SpringBoot uses a global configuration file with a fixed file name;
  1. application.properties
  2. application.yml
  • The configuration file is used to: modify the default SpringBoot automatic configuration. SpringBoot is automatically configured for us at the bottom;

YAML (YAML Ain’t Markup Language)

YAML A Markup Language: is A Markup Language

YAML isn’t Markup Language: not a Markup Language;

Markup language:

Previous configuration files; Most use the xxxx.xml file;

YAML: Data-centric, more suitable for configuration files than JSON, XML, etc.

YAML: configuration example

server:
  port: 8081
Copy the code

XML:

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

2. YAML syntax:

1. Basic grammar

K :(space)v: indicates a pair of key-value pairs (Spaces must exist).

Control hierarchy with space indented; All left-aligned columns are of the same level

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

Properties and values are also case-sensitive;

2, value writing

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; Special characters act as their intended meaning

Name: “zhangsan \n lisi” : output; Zhangsan newline lisi

‘ ‘: single quotation mark; Special characters are escaped, and the special characters end up just plain string data

Name: ‘zhangsan \n lisi’ : output; zhangsan \n lisi

Objects, maps (attributes and values) (key-value pairs) :

K: v: Writes the relationship between the object’s properties and values 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
 - pig
Copy the code

Inline writing

pets: [cat.dog.pig]
Copy the code
  • We can import the configuration file handler and be prompted to write the configuration later
<! -- Import config file handler, config file binding will be prompted -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
Copy the code

3. Config file value injection

Example: configuration file, application.yml under Resource

server:
  port: 8081

person:
  lastName: zhangsan
  age: 18
  boss: false
  birth: 2020/ 8/5
  maps: {k1:v1.k2:12}
  lists:
    - lisi
    - zhaoliu
  dog:
    name: The dog
    age: 12
Copy the code
  • JavaBean: Create a Person class in the bean package in com.xdr630.springboot
package com.xdr630.springboot.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/** * 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" : which properties in the configuration file are mapped one by one * * Container-supplied properties can only be enabled if the component is a container component@ConfigurationPropertiesFeatures * /
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

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

    public String getLastName(a) {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getAge(a) {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Boolean getBoss(a) {
        return boss;
    }

    public void setBoss(Boolean boss) {
        this.boss = boss;
    }

    public Date getBirth(a) {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Map<String, Object> getMaps(a) {
        return maps;
    }

    public void setMaps(Map<String, Object> maps) {
        this.maps = maps;
    }

    public List<Object> getLists(a) {
        return lists;
    }

    public void setLists(List<Object> lists) {
        this.lists = lists;
    }

    public Dog getDog(a) {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    @Override
    public String toString(a) {
        return "Person{" +
                "lastName='" + lastName + '\' ' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog +
                '} '; }}Copy the code
  • The Dog class under the bean package
package com.xdr630.springboot.bean;

public class Dog {
    private String name;
    private Integer age;

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge(a) {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString(a) {
        return "Dog{" +
                "name='" + name + '\' ' +
                ", age=" + age +
                '} '; }}Copy the code
  • ApplicationTests under com.xdr630.springboot package under test
package com.xdr630.springboot;

import com.xdr630.springboot.bean.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/* SpringBoot unit tests can be easily coded during testing to automate injection and other container functions */
@SpringBootTest
class ApplicationTests {
    @Autowired
    Person person;
    @Test
    void contextLoads(a) { System.out.println(person); }}Copy the code

Start the Test class:

1. The default UTF-8 characters in the properties configuration file in IDEA may be garbled

Adjust the

  • The properties configuration
#idea uses utF -8Person.last-name =��� person.age=18
person.birth=2020/8/5
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=dog
person.dog=age=15
Copy the code
  • Perform the test class

  • Example: Comment out the @ConfigurationProperties annotation in the Person class above and add the @Value annotation
@Component
//@ConfigurationProperties(prefix = "person")
/** * 
      
        * 
        * 
       */
public class Person {
    @Value("${person.last-name}")
    private String lastName;
    @Value("#{11*2}")
    private Integer age;
Copy the code
  • Start the test class:

2. Compare @Value to @configurationProperties

@ConfigurationProperties @Value
function Batch injection of properties in the configuration file Designate one by one
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
  • Configationproperties attribute name matching rules (Relaxed binding) — Person. firstName: uses the standard way — Person. first-name: Uppercase -person. first_name: uppercase _ – PERSON_FIRST_NAME: This is the recommended way to write system attributes
  • Configuration file yML or properties they can get the value;
  • If we just need to get a value in the configuration file for a business logic, use@Value;

    Example: Create HelloController class in controller package in com.xdr630.springboot
package com.xdr630.springboot.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @Value("${person.last-name}")
    private String name;

    @RequestMapping("/sayHello")
    public String sayHello(a){
        return "Hello"+name; }}Copy the code
  • Start the main program:

  • If we wrote a javaBean specifically to map to the configuration file, we would just use it@ ConfigurationProperties;

3. Verify configuration file injection value data

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

    /** * 
      
        * 
        * 
        * /
      

   //lastName must be in mailbox format
    @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
Copy the code
  • In the person. Add the properties
Person. The last - the person name =, dick, and harry. Age =18
person.birth=2020/8/5
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=dog
person.dog.age=15
Copy the code

4, @ PropertySource & @ ImportResource & @ Bean

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" : which of the following attributes in the configuration file are mapped one by one * * 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 {

    /** * 
      
        * 
        * 
        * /
      

   //lastName must be in mailbox format
   // @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;
Copy the code
  • Start the test class

  • Create the Spring configuration under Resource

ImportResource: Import the Spring configuration file for the configuration file to take effect.

There is no Spring configuration file in Spring Boot, and the configuration file written by us cannot be automatically recognized.

If you want Spring configuration files to work, load them in. The @importResource annotation is on a configuration class

@ImportResource(locations = {"classpath:beans.xml"})Import the Spring configuration file for it to take effectCopy the code

Do not write the Spring configuration file


      
<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="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>
Copy the code

The way SpringBoot recommends adding components to containers; A fully annotated approach is recommended

1. Configuration class @configuration ——>Spring Configuration file

2. Add components to the container using @beans

/ * * *@Configuration: indicates that the current class is a configuration class; To replace the previous Spring configuration file * * add the component * */ in the configuration file with the <bean><bean/> tag
@Configuration
public class MyAppConfig {

    // Add the return value of the method to the container; The default ID for this component in the container is the method name
    @Bean
    public HelloService helloService02(a){
        System.out.println("Config class @bean adds a component to the container...");
        return newHelloService(); }}Copy the code

##4, configuration file placeholder

1. Random number

The ${random value}, ${random.int}, ${random.long}
${random.int(10)}, ${random.int[1024.65536]}
Copy the code

2, the placeholder gets the previously configured value, if not can be: specifies the default value

person.last-name=Zhang SAN ${. Random uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=15
Copy the code

5, the Profile

1. Multiple Profile files

When we write the main profile, the file name can be application-{profile}.properties/yml

The default configuration of application.properties is used;

Specify the file configuration port number: spring.profiles. Active =dev to enable the specified port number

2. Yml supports multiple document blocks


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

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


---

server:
  port: 8084
spring:
  profiles: prod  # specify which environment to belong to
Copy the code

3. Activate the specified profile

1. Specify spring.profiles.active=dev in the configuration file

2, command line:

Java -jar spring-boot-02-config-0.0.1 -snapshot. jar –spring.profiles. Active =dev;

You can configure the incoming command line parameters directly during testing

3. Vm parameters;

​ -Dspring.profiles.active=dev

6. Loading position of configuration file

Springboot will scan the application.properties or application.yml file in the following location as the default configuration file for Spring Boot

– file:. / config /

– the file: /

– the classpath: / config /

– the classpath: /

  • For example, Priority 1 — 4

The configuration with a higher priority overwrites the configuration with a lower priority.

SpringBoot loads the master configuration file from all four locations; Complementary configuration; Example: HelloController under controller package

package com.xdr630.springboot.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello(a){
        return "hello"; }}Copy the code

Application. Properties in the Config directory of the project

server.port=8084Server.servlet. context-path=/boot02Copy the code
  • Start main program

We can also change the default configuration file location via spring.config.location

Once the project is packaged, we 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;

java -jar spring-boot-02-config-02-0.01.-SNAPSHOT.jar --spring.config.location=G:/application.properties
Copy the code

For example, create the application.properties file on the local drive F and add

server.port=8085
Copy the code

Package the above items and execute them in the terminal of IDEA

java -jar 02_springboot-02config-0.01.-SNAPSHOT.jar --server.config.additional-location==F:\application.properties
Copy the code

7. Loading sequence of external configuration

SpringBoot can also load configurations from the following locations; Priority from high to low; Note: Maven packages only package SRC resources (main, resource, etc.)

1. Command line parameters

All configurations can be specified on the command line

java -jar spring-boot-02-config-02-0.01.-SNAPSHOT.jar --server.port=8087  --server.context-path=/abc
Copy the code

Multiple configurations are separated by Spaces. — Configuration item = value

  • Alternatively, you can directly load the new configuration file by placing the configuration file in the same directory as the JAR package

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

8. Principle of automatic configuration

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

Reference to properties that can be configured in the configuration file

1.Automatic configuration principle:

1) When SpringBoot starts, load the main configuration class and enable the automatic configuration function @enableAutoConfiguration

2) @enableAutoConfiguration

  • 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 EnableAutoConfiguration values configured in 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,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,\
org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,\
org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,\
org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration
Copy the code

Each such xxxAutoConfiguration class is a component of the container and is added to the container; Use them for auto-configuration;

3) Each automatic configuration class provides automatic configuration function;

4), with HttpEncodingAutoConfiguration (Http code automatically configured as an example explain the principle of automatic configuration;

@Configuration   // indicates that this is a configuration class, which can also add components to the container, just as in the previous configuration file
@EnableConfigurationProperties(HttpEncodingProperties.class)  // Enable ConfigurationProperties for the specified class; Bind the corresponding values in the configuration file to HttpEncodingProperties; Add HttpEncodingProperties to the IOC container

@ConditionalOnWebApplication // The Spring underlying @Conditional annotation (Spring annotation version), depending on different conditions, if the specified conditions are met, the configuration in the whole configuration class will take effect; Check whether the current application is a Web application. If yes, the current configuration takes effect

@ConditionalOnClass(CharacterEncodingFilter.class)  // Check whether the current project has 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 it doesn't exist, the judgment is valid
/ / 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 {
  
  	// It has been mapped to the SpringBoot configuration file
  	private final HttpEncodingProperties properties;
  
   // If there is only one parameter constructor, the value of the parameter is taken from the container
  	public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
		this.properties = properties;
	}
  
    @Bean   // Add a component to the container whose values need to be retrieved from properties
	@ConditionalOnMissingBean(CharacterEncodingFilter.class) // Check that the container does not have this component.
	public CharacterEncodingFilter characterEncodingFilter(a) {
		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;
	}
Copy the code

Based on the current conditions, determine whether this configuration class is valid?

Once this configuration class takes effect; This configuration class adds various components to the container; The properties of these components are obtained from the corresponding Properties classes, each of which is bound to the 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 property class corresponding to a particular function

@ConfigurationProperties(prefix = "spring.http.encoding")  // Get the specified value from the configuration file and bind it to the bean's properties
public class HttpEncodingProperties {

   public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
Copy the code

Essence:

1) SpringBoot launches load a large number of automatic configuration classes

2) We need to see if the function we need is automatic configuration class written by SpringBoot default;

3) Let’s look at what components are configured in this auto-configuration class. (As long as the component we want to use is available, we don’t need to configure it.)

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

XxxxAutoConfigurartion: automatic configuration class;

Add components to the container

XxxxProperties: Encapsulates the related properties in the configuration file;

2, details

1. @Conditional derived annotations (native to Spring annotations for @Conditional)

Function: only if the conditions specified in @Conditional are true, can components be added to the container, and all contents in the configuration can be valid;

@Conditional extends annotations Function (Determine whether the current specified condition is 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 can only take effect under certain conditions.

How do we know which auto-configuration classes are in effect?

We can do this by enabling the debug=true attribute; To have the console print the auto-configuration report, so we can easily know which auto-configuration classes are in effect;

= = = = = = = = = = = = = = = = = = = = = = = = = AUTO - the CONFIGURATION REPORT = = = = = = = = = = = = = = = = = = = = = = = = = Positive matches: (automatic CONFIGURATION class enabled) ----------------- DispatcherServletAutoConfiguration matched: -@ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)- the @ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition)Negative matches: (no start, no match the automatic configuration of class) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ActiveMQAutoConfiguration: Did not match: - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory'(OnClassCondition)

   AopAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice' (OnClassCondition)
        
Copy the code