Chapter 3 of crossing SpringBoot - detailed explanation of SpringBoot configuration | section 1 - spring boot yaml configuration file in spring boot

yaml configuration file in Spring Boot

Premise:

With the help of IntelliJ IDEA, Maven construction tool and SpringBoot 2.3.4.
If officials need to use Maven, please read the tutorial: Download and installation of Maven build tool
If officials need to use IDEA, please read the tutorial: IntelliJ IDEA

More dry goods:

Please refer to Java learning materials: https://www.CJNB Learn by yourself.

definition:

What is Yaml?

Yaml is a superset of JSON. It is a convenient format for defining hierarchical configuration data. The structure level is clear, and the configuration is easy to read and use. To use yaml as the attribute configuration file, you need to add the snapeyaml library to the classpath. Spring Boot also integrates the snapeyaml library. For example, using Spring Boot starter web or Spring Boot starter will automatically add the snapeyaml library to the classpath.

requirement:

1. Suffix yml .yaml
2. Indent to indicate the hierarchical relationship: and the indent must use spaces instead of tab.
3. He is case sensitive.
The following is a simple application Open your eyes to the attribute configuration of YML configuration file.
In order to make SpringBoot generate data better, we need to add the following spring boot configuration processor dependency, which will only be called at compile time, so there is no need to worry about the impact on production
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

File application YML configuration:

application. Many things can be defined in the YML configuration file.

Object, map

Writing method: key: value (Note: the space after the colon cannot be omitted), as shown in the following code.
#Intermediate pair
com:
  example:
    boot:
      map:
        aaa: 123
        bbb: 456
        ccc: 789
#Inline writing
      map: {aaa: 123,bbb: 456,ccc: 789}

Array, set

Writing method: use - to define elements
#Mode 1:
com:
  example:
    boot:
      arr:
        - 1
        - 2
        - 3
      list:
        - a
        - b
        - c
      set:
        - true
        - false      
#Mode 2: in line writing
       arr: [1,2,3]
       list: [a,b,c]
       set: [true,false,true]

Attribute name

When the Java attribute name is in Hump form, for example: lastName
com:
  example:
    boot:
      # There are three ways to write attribute names
      lastName:  hello  yml1
      last-name: hello  yml2
      last_name: hello  yam3

placeholder

${} can reference other configurations and does not support inline writing
server:
   port: 8080
com:
  example:
    boot:
      arr:
        - 1
        - ${server.port}
        - 3

character string

1. It can be written directly
2. It can be enclosed in single quotation marks. 1 and 2 have the same effect. They will treat special characters as ordinary strings and will not handle them.
3 enclosed in double quotation marks: applicable to special characters inside, such as \ n
com:
  example:
    boot:
      # There are three ways to write attribute names
      #1.
      lastName:  hello \n yml1
      #2.
      last-name: 'hello \n yml2'
      #3.
      last_name: "hello \n yam3"

profile support

Single file multi environment configuration:

Multi environment configuration:

In real applications, there are often multiple environments (such as development, testing, production, etc.) with different database connections. Spring is needed at this time profile. Active has powerful functions. Its format is application - {profile} Properties, the prefix of application here cannot be changed, {profile} is defined by ourselves.
The figure below shows the total application YML file

Create application-dev.properties and application-prod.properties sub configuration files as shown in the figure below

The priority of external configuration is higher, as shown in the following figure:

Internal application YML file:

External application YML file:
We package and release the developed code. If the code passes the test in the test environment, it can be released for production. At this time, we modify the application The configuration of properties is very inconvenient. Then we need to create the following external files and run the cmd command.


Storage location of configuration files

Write the XxxProperties config configuration object class

Demo: receive application with your own object YML configuration file (that is, injecting values into objects). The object here is a map
Class defines a map, list, set, arr, simulation, defines the naming of lastName hump, and uses lombok to generate its get and set methods.
lombok usage: import lombok, refer to pom dependency at the end of the text; Just use @ Data annotation

package com.example.boot.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Data//Using lombok plug-in to automatically generate get and set methods
@ConfigurationProperties(prefix ="com.example.boot")//Prefix specifies a prefix
public class XxxProperties {
    //To receive with a map, there must be a getter setter method.
    private Map<String,Object> map;

    private Integer [] arr;
    private List<String> list;
    private Set<Boolean> set;
    private String lastName;
}

Write BootApplication startup class

package com.example.boot;

import com.example.boot.config.XxxProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import java.util.Arrays;

@EnableConfigurationProperties(XxxProperties.class )//Register the XxxProperties class and declare it as a bean.
@SpringBootApplication
public class BootApplication implements ApplicationRunner {

	public static void main(String[] args) {
		SpringApplication.run(BootApplication.class, args);
	}
	
	//Inject xxproperties class
	@Autowired
	private XxxProperties properties;

	//1. Implement the ApplicationRunner interface and generate the run method for testing. (after the program starts, it will call back for execution)
	//2. Test in unit test class
	@Override
	public void run(ApplicationArguments args) throws Exception {
		System.out.println(properties.getMap());
		System.out.println(Arrays.asList(properties.getArr()));
		System.out.println(properties.getList());
		System.out.println(properties.getSet());
		System.out.println(properties.getLastName());
	}
}

Expand the support of profile

application. Configuration of properties file

1. Configure profile


2. Activate profile
Method 1: activate through the main configuration file, as shown in the following figure

Method 2: right click to enter edit configuration


Other scenarios: running two environments at the same time

application.properties is better than application YML high priority



Test:

1. Package in mawen environment.
2. Then enter the project directory (i.e. the target directory in your source code), where my local directory is the main: / users / documents / springboot learning experience / spring boot config
Open the program - cmd-0.jar - snap-boot.3 Just press enter
4. Finally, check the console output

pom.xml: dependencies

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.4.RELEASE</version>
		<relativePath/>
	</parent>
	<groupId>com.example</groupId>
	<artifactId>1010</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>boot</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
<!--	web  	-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
<!--	configuration-processor	-->

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
<!--	lombok	-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
<!--	test	-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Summary:

To be improved
This tutorial is based on the latest spring boot starter parent: 2.3.4 release. At present, many leaders have written tutorials on spring boot. If there are similarities, please forgive me

Tags: Spring Boot yml Configuration

Posted by Osorene on Wed, 11 May 2022 09:07:54 +0300