SpringBoot configuration file (.properties+yml)


Configuration files in SpringBoot

1. The role of the configuration file

All important data in the entire project are configured in the configuration file, such as:
● database connection information (including user name and password settings);
● project startup port;
● third-party system Call secret key and other information;
● Common logs and exception logs for finding and locating problems, etc.

2. SpringBoot configuration file format

  1. xxx.properties(the format of the default configuration file)
  2. xxx.yml(new, improved configuration file format)
  3. When there are .propertiesboth .ymland the same configuration item in the two configuration files, the Spring Boot project will use the .properties configuration item with higher priority as the final configuration item. The priority of the configuration file in the properties format is higher than that of yml
  4. Two different configuration files, properties and yml, are allowed in a project, but it is not recommended to use only two formats of configuration files in a project. The idea of ​​the
    community version needs to install the Spring Tools plug-in, and then there will be code prompts when using the properties configuration item

propertiesBasic syntax

Properties are configured in the form of key-value, and the key and value are connected by "=". If it is your own configuration information, then you can define a Key with any name in the format of key=value

#端口号
server.port=7070
#数据库的配置信息
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/database_name?characterEncoding=utf8&useSSL=false
spring.datasource.name=root
spring.datasource.password=root

read configuration file

If you want to actively read the content in the configuration file in the project, you can use @Valueannotations to read the format used
@Value by annotations , as shown in the following code:“${}”

@Component
public class ReadProperties {
    
    
    @Value("${server.port}")
    String port;
    @Value("${spring.datasource.url}")
    String url;

    // 初始化时执行的方法
    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(this.port);
        System.out.println(this.url);
        System.out.println();
    }
}


@Component will be injected into the framework when Spring Boot starts, and the @PostConstruct initialization method will be executed when injected into the framework , and the configuration information can be read at this time

operation result

insert image description here

properties Disadvantage Analysis

  1. It is very troublesome to set multiple parameters for an object, and it needs to be written from the beginning to the end
  2. There are redundant configuration items
    insert image description here
    To solve this problem, you can use a configuration file in yml format

3. Use of yml configuration file

yml is YMAL is an abbreviation, its full name Yet Another Markup Language translated into Chinese is "another markup language".
yml is a highly readable, easy-to-understand format for expressing data serialization. Its syntax is similar to other high-level languages, and it can
simply express data forms such as lists (arrays), hash tables, and scalars. It uses whitespace symbols for indentation and features that depend heavily on appearance, and is especially
suitable for expressing or editing data structures, various configuration files, etc.
The biggest advantage of yml is that it can be cross-language , not only Java can use golang, python can also use yaml as a configuration file

yml basic syntax

yml is a tree structure configuration file, its basic syntax is "key: value", note that the key and value are composed of English sweat plus spaces, and the spaces cannot be
omitted

Note: There must be a space after the colon!
Two spaces are required for the second level and the previous level

server:
  port: 6060
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/database_name?characterEncoding=utf8&useSSL=false
    name: root

insert image description here

configuration object

We can also configure objects in yml, as follows

student:
  id: 1
  name: 张三
  age: 18

There is another way of writing similar to JSON, pay attention to adding spaces !

student: {
    
    id: 1,name: 张三,age: 18}

At this time, it cannot be used @Valueto read the objects in the configuration. At this time, another annotation should be used @ConfigurationProperties
to read. The specific implementation is as follows

Read configuration file method 2: @ConfigurationProperties read an entity class

1. Map a set of objects in the configuration file to a class

Note that get and set methods must be added, otherwise it cannot be mapped, and the object name must correspond to the configuration file

@Component//spring 启动时直接将配置文件映射到当前类属性
@ConfigurationProperties(prefix = "student")//配置yml文件中的key,prefix可以省略
public class Student {
    
    
    private int id;
    private String name;
    private int age;


    @Override
    public String toString() {
    
    
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

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

    public int getAge() {
    
    
        return age;
    }

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

2. Use the injection method to inject in other classes

@Component
public class ReadYml {
    
    
    @Autowired
    Student student;

    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(student);
        System.out.println();
    }
}

Start SpringBoot running results

insert image description here

configuration collection

The configuration file can also configure the list collection, as shown below
Note: spaces!

lists:
  language:
    - java
    - python
    - c++
    - golang

Similar to the configuration object, you can write long lines

lists: {
    
    language: [java,python,c++,golang]}

The reading of the collection is the same as the object, and it is also used to @ConfigurationPropertiesread. The specific implementation is as follows:
Note that the get and set methods must be added, otherwise it cannot be mapped, and the object name must correspond to the configuration file.

insert image description here

@Component// spring启动时直接将配置文件映射到类属性
@ConfigurationProperties("lists")
public class MyList {
    
    
    private List<String> language;

    public List<String> getLanguage() {
    
    
        return language;
    }

    public void setLanguage(List<String> language) {
    
    
        this.language = language;
    }
}

Use injection to inject in other classes

@Component
public class ReadYml {
    
    
    @Resource
    private MyList myList;
    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(myList.getLanguage());
        System.out.println();
    }
}

operation result

insert image description here

yml configures different data types and null

# 字符串
string.value: Hello
# 布尔值,true或false
boolean.value: true
boolean.value1: false
# 整数
int.value: 10
int.value1: 0b1010_0111_0100_1010_1110 # ⼆进制
# 浮点数
float.value: 3.14159
float.value1: 314159e-5 # 科学计数法
# Null,~代表null
null.value: 

Note: add single and double quotes to the value

yml configuration file content

str1: hello\nworld
str2: 'hello\nworld'
str3: "hello\nworld"

Read configuration file and print

@Component
public class ReadYml {
    
    
    @Autowired
    private Student student;
    @Resource
    private MyList myList;
    @Value("${str1}")
    private String str1;
    @Value("${str2}")
    private String str2;
    @Value("${str3}")
    private String str3;
    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println();
    }
}

operation result

insert image description here

  1. If it is a string type, you can not add single quotes or double quotes
  2. If the effect of adding single quotes and not adding (any symbol) is the same, it will escape the special symbols in the string and make it a normal character
  3. If double quotes are added, the special characters of the string will not be escaped, and will be executed correctly according to the semantics. For example, the above \n will become a newline

4. properties vs yml

  1. yml syntax is more concise
  2. yml is more versatile across languages, it not only supports the Java language but also supports golang and python
  3. yml supports more data types
  4. The configuration file in yml format is more error-prone when writing, while properties is more traditional and complex, but it is less error-prone
  5. propertieshas higher priority

5. Five ways to read configuration files in SpringBoot

Suppose you want to read server.port in the configuration file

use @Value

@Component
public class ReadProperties {
    
    
    @Value("${server.port}")
    String port;
    // 初始化时执行的方法
    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(this.port);
        System.out.println();

    }

}

Use @ConfigurationProperties to read configuration files (get object)

@Component//spring 启动时直接将配置文件映射到当前类属性
@ConfigurationProperties(prefix = "student")//配置yml文件中的key,prefix可以省略
public class Student {
    
    
    private int id;
    private String name;
    private int age;


    @Override
    public String toString() {
    
    
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

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

    public int getAge() {
    
    
        return age;
    }

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

Use Environment to read configuration as a file

org.springframework.core.env.EnvironmentUse the Environment object of Environment
to read the configuration file by using the getProperty of the Environment to give the key value of the parameter configuration file

@Component
public class ReadProperties {
    
    
    @Resource
    private Environment environment;
    // 初始化时执行的方法
    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(environment.getProperty("server.port"));
        System.out.println();

    }

}

@PropertySource

Using @PropertySourceannotations can be used to specify to read a certain configuration file, such as specifying to read app.propertiesthe configuration content of the configuration file. For
example, if I have multiple properties configuration files, I need to specify the name of another configuration file to be read
. configuration file.@PropertySource.properties

insert image description here

@Component
@PropertySource("app.properties")//读取指定配置文件
public class ReadProperties {
    
    
    @Value("${server.port}")
    private String port;

    // 初始化时执行的方法
    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(this.port);
        System.out.println();
    }

}

If garbled characters appear

@PropertySource(value = "dev.properties", encoding = "utf-8")

Then set the character set of idea

Use the native way to read the configuration file

@Component
@PropertySource("app.properties")//读取指定配置文件
public class ReadProperties implements InitializingBean {
    
    

    @Override
    public void afterPropertiesSet() throws Exception {
    
    
        Properties properties = new Properties();
        try (InputStreamReader inputStreamReader = new InputStreamReader
                (this.getClass().getClassLoader().getResourceAsStream("app.properties"),StandardCharsets.UTF_8)) {
    
    
                    properties.load(inputStreamReader);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        System.out.println();
        System.out.println(properties.getProperty("server.port"));
        System.out.println();
    }
}

6. Multi-environment configuration files

In actual development, there are often multiple configuration files, at least three, the development environment, the online environment, and the default configuration file. To
configure a file in different environments, you only need to change the configuration file application.propertiesin .

# 设置配置文件的环境 (开发环境 OR 生产环境)
spring.profiles.active=dev

The format of application and . is a fixed format, and -the latter is the custom name. For example, it is specified application-port.propertiesas a configuration file here
insert image description here

More system configuration items Spring official website


Guess you like

Origin blog.csdn.net/weixin_53946852/article/details/129748398