Spring Boot YAML configuration

Keywords: Java Spring Boot Back-end

  catalogue

1. YAML syntax

1. Basic grammar

2. Data type

2. Configuration injection

1,@ConfigurationProperties & @Value

2,@PropertySource&@ImportResource&@Bean

 3,Profile

1. Multiple profile files

2. Specify profile

3. Profile location

4. External configuration

5. Auto configuration

1. Automatic configuration principle

2. @ Conditional derived annotation (the native @ Conditional function of Spring annotation version)

         SpringBoot uses a global configuration file to modify the default value of SpringBoot automatic configuration, and the configuration file name is fixed

  • application.properties
  • application.yml

1. YAML syntax

1. Basic grammar

  • Case sensitive
  • Use indentation to represent hierarchical relationships
  • tab is not allowed for indentation, only spaces are allowed
  • The number of indented spaces is not important, as long as the elements of the same level are aligned to the left
  • '#' indicates a comment
server:
  port: 8080
  servlet:
    context-path: /demo

2. Data type

  • Object: a collection of key value pairs, also known as mapping / hashes / dictionary
  • Array: a set of values arranged in order, also known as sequence / list
  • scalars: single, non separable values

Reference address: YAML tutorial

2. Configuration injection

1,@ConfigurationProperties&@Value

configuration file

person:
  name: shinb
  age: 20
  boss: false
  birth: 2021/10/10
  maps: {k1: v1,k2: 12}
  lists:
    ‐ lisi
    ‐ zhaoliu
  dog:
    name: puppy
    age: 8

java bean

/**
 * Map the value of each attribute configured in the configuration file to this component
 * @ConfigurationProperties Tell 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 is mapped one by one
 * @ConfigurationProperties Overwrite @ Value
 * The @ ConfigurationProperties function provided by the container can only be used if this component is a component in the container;
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {

    @Value("${person.name}")
    private String name;
    @Value("#{12*2}")
    private Integer age;
    @Value("true")
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

    //getters setters
}

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

    //getters setters    
}

2,@PropertySource&@ImportResource&@Bean

@PropertySource: loads the specified configuration file

/**
* Map the value of each attribute configured in the configuration file to this component
* @ConfigurationProperties: Tell SpringBoot to bind all the properties in this class to the relevant configuration in the configuration file;
* prefix = "person": Which of the following attributes in the configuration file is mapped one by one
*
* The @ ConfigurationProperties function provided by the container can only be used if this component is a component in the container;
* @ConfigurationProperties(prefix = "person")Get the value from the global configuration file by default;
*
*/
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")

@ImportResource: import the Spring configuration file to make the contents in the configuration file take effect

To make the Spring configuration file effective, load it and mark @ ImportResource on a configuration class

@ImportResource(locations = {"classpath:beans.xml"})

<?xml version="1.0" encoding="UTF‐8"?>
<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.shinb.demo.service.HelloService"></bean>
</beans>

SpringBoot does not recommend adding components by importing configuration files. Full annotation is recommended

  1. Create Configuration class @ Configuration    ---->  Spring Configuration file  
  2. Use @ Bean in the configuration class to add components to the container
/**
 * @Configuration Indicates that the current class is a configuration class; Is to replace the previous Spring configuration file
 * @Bean Equivalent to < bean > < bean / >
 */
public class MyDemoConfig {

    @Bean
    public HelloService getHelloService(){
        return new HelloService();
    }
}

 3,Profile

1. Multiple profile files

         When we write the main configuration file, the file name format can be application-{profile}.properties/yml. The configuration of application.properties is used by default

  • application.yml
  • application-dev.yml
  • application-proc.yml
  • application-uat.yml

2. Specify profile

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

spring:
  profiles:
    active: dev

         command line

java -jar spring-boot-demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

        JVM parameters

-Dspring.profiles.active=dev 

3. Profile location

         springboot startup will scan the application.properties or application.yml file in the following location as the default configuration file of Spring boot. The priority is from high to low, and the configuration with high priority will overwrite the configuration with low priority.

  • –file:./config/
  • –file:./
  • –classpath:/config/
  • –classpath:/ 

        SpringBoot will load all the main configuration files from these four locations; Complementary configuration

         We can also change the default configuration file location through spring.config.location. After the project is packaged, we can use the form of command line parameters to specify the new location of the configuration file when starting the project. The specified configuration file and these configuration files loaded by default work together to form a complementary configuration.

        java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --                                                                        spring.config.location=G:/application.properties

4. External configuration

1. Command line 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

         Multiple configurations are separated by spaces-- Configuration item = value

2. JNDI attribute from java:comp/env

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

4. Operating system environment variables

5. The random. * property value of randomvaluepropertysource configuration is searched from the jar package to the jar package, and the profile is loaded first

6. application-{profile}.properties or application.yml (with spring.profile) configuration file outside the jar package

7. Load the application-{profile}.properties or application.yml (with spring.profile) configuration file inside the jar package without profile

8. 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 the jar package

10. @ PropertySource on @ configuration annotation class

11. Default properties specified through SpringApplication.setDefaultProperties

 Refer to official documents

5. Auto configuration

1. Automatic configuration principle

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

2) @ EnableAutoConfiguration function

  • Use EnableAutoConfigurationImportSelector to import some components into the container;
  • You can view the contents of the selectImports() method;
  • List configurations = getCandidateConfigurations(annotationMetadata, attributes); Get candidate configuration

SpringFactoriesLoader.loadFactoryNames()

Scan META ‐ INF/spring.factories under all jar package Classpaths

Wrap the contents of these scanned files into properties objects

Get the values corresponding to the EnableAutoConfiguration.class class (class name) from properties, and then add them to the container

All EnableAutoConfiguration values configured in META-INF/spring.factories under the classpath are added to the container. Each such xxxAutoConfiguration class is a component in the container and is added to the container for automatic configuration

3) Take Http encoding autoconfiguration as an example to explain the principle of autoconfiguration

@Configuration(
    proxyBeanMethods = false
) //Indicates that this is a configuration class. Like the previously written configuration file, you can also add components to the container

@EnableConfigurationProperties({ServerProperties.class}) //Starts the of the specified class
//ConfigurationProperties function; Bind the corresponding value in the configuration file with ServerProperties; And add the ServerProperties to the ioc container

@ConditionalOnWebApplication(
    type = Type.SERVLET
)//Spring bottom @ Conditional annotation (spring annotation version), according to different conditions
//If the specified conditions are met, the configuration in the entire configuration class will take effect; Judge whether the current application is a web application. If so, the current configuration class will take effect

@ConditionalOnClass({CharacterEncodingFilter.class}) //Determine whether the current project has this class
CharacterEncodingFilter;SpringMVC Filter for garbled code resolution in

@ConditionalOnProperty(
    prefix = "server.servlet.encoding",
    value = {"enabled"},
    matchIfMissing = true
) //Judge whether a spring.http.encoding.enabled configuration exists in the configuration file; If it does not exist, the judgment is also valid
//Even if pring.http.encoding.enabled=true is not configured in our configuration file, it will take effect by default;
public class HttpEncodingAutoConfiguration {

    //He has mapped to the SpringBoot configuration file
    private final Encoding properties;

    //When there is only one constructor with parameters, the value of the parameter will be taken from the container
    public HttpEncodingAutoConfiguration(ServerProperties properties) {
        this.properties = properties.getServlet().getEncoding();
    }

    @Bean    //Add a component to the container. Some values of this component need to be obtained from properties
    @ConditionalOnMissingBean //Determine that the container does not have this component
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.RESPONSE));
        return filter;
    }

         Determine whether this configuration class is effective according to different current conditions,   Once the configuration class takes effect; This configuration class will add various components to the container; The properties of these components are obtained from the corresponding properties classes, and each property in these classes is bound to the configuration file;

  4) All properties that can be configured in the configuration file are encapsulated in the xxxproperties class; The attribute class corresponding to a function can be referenced for what can be configured in the configuration file

@ConfigurationProperties(
    prefix = "server",
    ignoreUnknownFields = true
)//Get the specified value from the configuration file and bind it with the properties of the bean
public class ServerProperties {

Summary:

  • SpringBoot boot will load a large number of auto configuration classes
  • Let's see if the functions we need have the auto configuration class written by SpringBoot by default;
  • Let's look at which components are configured in this automatic configuration class; (as long as the components we want to use are, we don't need to configure them again)
  • When adding components to the automatic configuration class in the container, some properties will be obtained from the properties class. We can specify the values of these attributes in the configuration file;

Xxxautoconfiguration: automatic configuration class; Add components to container

Xxxproperties: encapsulates related properties in the configuration file;

2. @ Conditional derived annotation (the native @ Conditional function of Spring annotation version)

         Function: only when the conditions specified by @ Conditional are true can components be added to the container and all contents in the configuration configuration take effect.

@Conditional extension annotationFunction (judge whether the current specified conditions are met)
@ConditionalOnJavaWhether the java version of the system meets the requirements
@ConditionalOnBeanThe specified Bean exists in the container
@ConditionalOnMissingBeanThe specified Bean does not exist in the container
@ConditionalOnExpressionMeet the SpEL expression specification
@ConditionalOnClassThere are specified classes in the system
@ConditionalOnMissingClassThere is no specified class in the system
@ConditionalOnSingleCandidateThere is only one specified Bean in the container, or this Bean is the preferred Bean
@ConditionalOnPropertyWhether the specified attribute in the system has the specified value
@ConditionalOnResourceDoes the specified resource file exist under the classpath
@ConditionalOnWebApplication        It is currently a web environment
@ConditionalOnNotWebApplicationThe current is not a web environment
@ConditionalOnJndiThe specified item exists in JNDI

Posted by devai on Sun, 31 Oct 2021 21:03:00 -0700