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

  port: 8081
Copy the code


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

    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

		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

 - cat
 - dog
 - pig
Copy the code

Inline writing

pets: []
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 -->
Copy the code

3. Config file value injection

Example: configuration file, application.yml under Resource

  port: 8081

  lastName: zhangsan
  age: 18
  boss: false
  birth: 2020/ 8/5
  maps: {k1:v1.k2:12}
    - lisi
    - zhaoliu
    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.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 * /
@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) { = dog;

    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) { = name;

    public Integer getAge(a) {
        return age;

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

    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 */
class ApplicationTests {
    Person person;
    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
Copy the code
  • Perform the test class

  • Example: Comment out the @ConfigurationProperties annotation in the Person class above and add the @Value annotation
//@ConfigurationProperties(prefix = "person")
/** * 
public class Person {
    private String lastName;
    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;

public class HelloController {
    private String name;

    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

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

    /** * 
        * /

   //lastName must be in mailbox format
    private String lastName;
    private Integer age;
    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
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 = {""})
@ConfigurationProperties(prefix = "person")
public class Person {

    /** * 
        * /

   //lastName must be in mailbox format
   // @Email
    private String lastName;
    private Integer age;
    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=""

    <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
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
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
    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.long}
${}, ${[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}
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 is used;

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

2. Yml supports multiple document blocks

  port: 8081
    active: prod

  port: 8083
  profiles: dev


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

3. Activate the specified profile

1. Specify 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;


6. Loading position of configuration file

Springboot will scan the 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;

public class HelloController {
    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:/
Copy the code

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

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:\
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
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) { = 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();
		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


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)

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