[Spring Boot] (2) Exploration tour of Spring Boot configuration files


foreword

Configuration files play an important role in software development, allowing us to tweak and configure the behavior of the application without changing the source code . For a modern framework like Spring Boot, the configuration file is the key to its flexibility and ease of use. With proper configuration, we can seamlessly migrate applications from development environments to testing and production environments, while providing specific configurations for different deployment environments .

This article will delve into all aspects of Spring Boot configuration files, from basic syntax to settings in different environments, to help readers fully understand and flexibly apply the relevant knowledge of configuration files. Next, I will step through the different aspects of the configuration file, let us embark on this journey of discovery about Spring Boot configuration.

1. The role of the configuration file

A configuration file is a way of externalizing configuration to store information such as parameters, options, and settings for an application. The main functions of the configuration file are as follows :

  1. Flexibility and configurability : By separating configuration information from code, applications become more flexible and configurable . This means that we can adjust the behavior of the application to meet different business needs and environmental requirements by simply modifying the configuration files without modifying the code.

  2. Reduced coupling : When configuration information is externalized, the dependencies between different components of an application are reduced . In this way, when a certain configuration needs to be changed, only the configuration file needs to be modified without affecting other parts of the code, which reduces the coupling between codes and makes the code easier to maintain and expand.

  3. Convenient deployment and management : Through the configuration file, we can separate the application settings from the code, so that when deploying, only the configuration file needs to be replaced or updated without recompiling the entire code. At the same time, configurations in different environments can be managed through different configuration files, thus simplifying the deployment and management of applications in different environments.

  4. Security : Sensitive information (such as database passwords, API keys, etc.) should generally not be hardcoded in code, but stored in configuration files. This avoids exposing sensitive information in code repositories or released applications, improving application security.

  5. Internationalization and localization : Configuration files can be used to store text and localization information in different languages. In this way, the application program can read the corresponding configuration file according to the user's language environment, so as to realize the requirements of internationalization and localization.

Second, the format of the configuration file

2.1 Spring Boot configuration file format

Spring Boot supports multiple configuration file formats, the common ones are properties and yml (YAML) . Different formats are suitable for different scenarios, and developers can choose the configuration file format that suits them according to actual needs.

1. properties format

properties is a text format of key-value pairs, each line contains a property and the corresponding value . Its format is similar to: key=value. In Spring Boot, various properties can be configured using the properties format. For example:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=myusername
spring.datasource.password=mypassword
server.port=8080

2. yml (YAML) format

YAML is a concise and easy-to-read data serialization format. Its full name Yet Another Markup Language, translated into Chinese, is "another markup language". It缩进 expresses hierarchical relationships in the form of and supports data structures such as lists and maps . In Spring Boot, configuration files in yml format are usually suffixed with .ymlor.yaml . Compared with the properties format, the yml format is more flexible and easier to write. For example:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: myusername
    password: mypassword
server:
  port: 8080

In a Spring Boot project, configuration files in properties and yml formats can theoretically be used at the same time, and they can coexist in the same project. When the properties and yml configuration files exist at the same time and have the same configuration items, the configuration in the properties file will have priority, that is, the configuration with the same name in the yml file will be overwritten .

  • This mechanism of configuration priority enables developers to choose more flexibly to configure different parameters in properties or yml format, and to organize and manage different types of configuration information in different configuration files.
  • For example, regular, relatively simple configuration items can be placed in properties files, while complex, structured configuration items can be placed in yml files to improve readability and maintainability.

However, although configuration files in both formats are theoretically allowed, in practical projects, a unified configuration file format is usually chosen. Doing so has the following benefits:

  1. Unified Maintenance : Using a unified configuration file format reduces maintenance costs, confusion and errors. All configuration information is concentrated in the same format, which is easier for the development team to maintain and manage in a unified manner.

  2. Reduced failure rate : The unified configuration file format avoids conversion and adaptation problems between different formats, reducing potential errors and failures.

  3. Legibility : Using a unified configuration file format can improve communication and understanding among team members and reduce confusion caused by format differences.

  4. Standardization : A unified configuration file format helps to form norms and best practices, improving project maintainability and stability.

2.2 The difference between properties and yml

When choosing a configuration file format, you can consider the following aspects:

  1. Grammatical structure : The properties format uses a simple key-value pair structure , which is suitable for simple configuration scenarios. The yml format uses indentation to represent hierarchical relationships , which can show complex configuration structures more clearly, and is suitable for handling more complex configurations.

  2. Legibility : The yml format is more readable and maintainable due to its indented structure . In contrast, the properties format may appear verbose and unintuitive when there are many configurations or deep nesting .

  3. Extensibility : The yml format supports richer data structures such as lists and maps, which makes it more flexible when dealing with complex configurations . The properties format can only represent simple key-value pairs .

  4. Key name constraints : Key names in the properties format cannot contain spaces and must follow certain naming conventions . The key names in the yml format can contain spaces, which is more flexible .

Overall, for simple configurations, the properties format may be more intuitive and convenient; for complex configurations, the readability and flexibility of the yml format make it a better choice. In practical applications, choosing the appropriate configuration file format is an important decision based on the needs of the project and the team's preferences. Spring Boot provides comprehensive support for the two formats, which can be selected and used according to the actual situation of the project.

Three, properties configuration file

3.1 properties basic syntax

The properties configuration file is a simple key-value pair text format, each line contains a property and the corresponding value, and the equal sign "=" is used to connect the key name and the key value. The basic syntax is as follows:

# 配置项目的端口号
server.port=8084
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=
utf8
spring.datasource.username=root
spring.datasource.password=root

PS: Use "#" in the configuration file to add comment information.

3.2 Reading of configuration files

@Valueand @ConfigurationPropertiesare two common ways to read configuration values ​​in Spring Boot, both of which can be used to bind property values ​​in configuration files to Java objects for easy use in code.

1. @ValueNotes:

@ValueIt is an annotation in the Spring framework, which can be directly used to inject the attribute value in the configuration file into the attribute in the Spring Bean . By using annotations on the properties @Valueand specifying the key name of the property (such as ${key}), Spring Boot will automatically read the corresponding value from the configuration file and assign it to the property.

Suppose we have a application.propertiesconfiguration file with the following content:

app.name=My Application
app.version=1.0.0

Then we can use annotations in Spring Bean @Valueto read these configuration items:

@Component
public class MyBean {
    
    
    @Value("${app.name}")
    private String appName;

    @Value("${app.version}")
    private String appVersion;

    @PostConstruct
    public void doPostConstruct(){
    
    
        System.out.println("appName: " + appName);
        System.out.println("appVersion: " + appVersion);
    }
}

The above code represents the creation of one MyBeanthat uses @Valueannotations to read the attribute values ​​in the configuration file, and @PostConstructprints out the read attribute values ​​in the method marked by the annotations. Run the startup class, and you can see that the console prints out relevant configuration information:

2. @ConfigurationPropertiesComments:

@ConfigurationPropertiesIt is an annotation provided by Spring Boot dedicated to reading configuration file properties. It can bind the attribute value in the configuration file to the corresponding attribute in the Java object, and provides a more flexible configuration item binding function . It should be noted that @ConfigurationPropertieswhen using annotations, a prefixparameter needs to be provided to specify the prefix of the attribute in the configuration file for attribute matching.

Suppose we have a application.propertiesconfiguration file with the following content:

app.name=My Application
app.version=1.0.0

Then we can create a Java class and use @ConfigurationPropertiesannotations to read these configuration items:

@Component
@Setter
@ConfigurationProperties("app")
public class AppConfig {
    
    
    private String name;
    private String version;

    @PostConstruct
    public void init() {
    
    
        System.out.println("appName: " + name);
        System.out.println("appVersion: " + version);
    }
}

In the above example, @ConfigurationProperties(prefix = "app")the attribute prefix in the configuration file is specified as "app", and Spring Boot will automatically read the configuration items prefixed with "app", and assign the corresponding value to the corresponding attribute of the AppConfigclass.

注意,此时一定要提供 Setter 方法才行,此处我使用的是Lombok工具中的 @Setter 注解为我提供 Setter 方法。

Run the startup class:

The difference between the two:

  • @ValueAnnotations are used to directly inject a property value in a configuration file into a Spring Bean property. Suitable for simple configuration item reading.
  • @ConfigurationPropertiesAnnotations are used to bind multiple attribute values ​​in a configuration file to multiple attributes in a Java object, providing a more flexible configuration item binding function and supporting the configuration of complex data structures. Suitable for complex configuration item reading.

To sum up, @Valueand @ConfigurationPropertiesare common ways to read configuration values, which way to choose depends on the actual needs and the complexity of the configuration items.

3.3 Analysis of advantages and disadvantages of properties

3.3 Analysis of advantages and disadvantages of properties:

advantage:

  1. Simple and intuitive : The properties configuration file adopts a simple key-value pair format, which is easy to write and read, and is very intuitive and convenient for simple configuration items.

  2. Wide support : The properties format is a common configuration file format that is supported in most programming languages ​​and frameworks, so it is suitable for various application scenarios.

  3. Clear configuration : Since the properties configuration file expresses the correspondence between configuration items and configuration values ​​in the form of key-value pairs, the configuration is clear and easy to maintain and modify.

  4. Fast reading : The format of the properties configuration file is simple, and the reading speed is fast, which is more efficient for quickly obtaining configuration information.

shortcoming:

  1. Lack of structure : The properties configuration file only supports simple key-value pair structures, and cannot represent complex data structures, such as nested objects and lists. When the configuration item is more complex, it may not be flexible enough.

  2. Key name restriction : The key names in the properties configuration file cannot contain special characters such as spaces, and must follow certain naming conventions, which is not flexible enough.

  3. Multi-line values ​​are not supported : values ​​in the properties configuration file must be written in one line, and cross-line representation of configuration values ​​is not supported, which may not be convenient when configuring long text.

To sum up, the properties configuration file is a simple and practical configuration format, suitable for simple configuration scenarios. However, the properties format has some obvious disadvantages, such as lack of structure, key name restrictions, redundancy, etc., which may limit its use when the configuration item is more complex. In actual development, according to the configuration complexity and requirements of the project, you can choose a more flexible configuration file format, such as yml format, to meet more complex configuration requirements.

4. Description of yml configuration file

4.1 yml basic syntax

The yml format uses indentation to indicate hierarchical relationships, supports data structures such as lists and maps, and features such as comments and multi-line text. The basic syntax is as follows:

  1. key-value pair:
key1: value1
key2: value2
  1. list:
key3:
  - item1
  - item2
  1. Nested mappings:
key4:
  subkey1: value1
  subkey2: value2
  1. Multiline text:
key5: |
  This is a multiline text.
  It can span multiple lines without escaping special characters.
  1. Notes:
# This is a comment.
key6: value6  # This is another comment.

yml 配置文件的读取和 properties 配置文件读取方法一致。

4.2 yml use cases

Suppose we have a application.ymlconfiguration file with the following content:

app:
  name: My Application
  version: 1.0.0
  author: 张三

server:
  port: 8080

database:
  url: jdbc:mysql://localhost:3306/mydb
  username: myusername
  password: mypassword

In the above case, the configuration file in yml format shows a variety of commonly used configuration methods. appThe section is a map that contains attributes such as the application's name, version, and author. serverThe section is a simple key-value pair specifying the project's launch port. databaseThe section is a nested map that contains properties related to the database connection.

4.3 Analysis of advantages and disadvantages of yml

advantage:

  1. Flexible and easy to read : The yml format uses indentation to represent hierarchical relationships, making it easy to read and write. Features such as lists, maps, and multi-line text are supported, which can more clearly display complex configuration structures and improve the readability and maintainability of configuration files.

  2. Support for complex data structures : The yml format supports lists and nested maps, which can represent more complex data structures and are suitable for processing complex configuration items.

  3. Support comments : yml format allows comments to be added, and explanatory comment information can be added to the configuration file to facilitate understanding and explanation of the meaning of configuration items.

  4. Not limited by key names : key names in yml format can contain special characters such as spaces, and do not need to follow specific naming conventions, which is more flexible.

shortcoming:

  1. Learning cost : Compared with the properties format, the syntax of the yml format may be more complicated, and it takes some time for beginners to adapt and learn.

  2. Error-prone : Since the yml format relies on indentation to represent the hierarchical relationship, if the indentation is incorrect, it may cause configuration parsing errors, increasing the possibility of errors.

To sum up, the yml configuration file is a flexible and easy-to-read configuration format, suitable for complex configuration scenarios. It has the advantages of being flexible and easy to read, supporting complex data structures, supporting annotations and not being restricted by key names, which can improve the readability and maintainability of configuration files. However, the yml format also has some disadvantages, such as high learning cost and error-prone, which needs to be developed

5. Set configuration files in different environments

In Spring Boot, different environments can be distinguished through different configuration files, such as development environment, test environment and production environment. Spring Boot will load application.yml(or application.properties) as the main configuration file by default, but different configuration files can be loaded according to different environments. Through the naming rules, Spring Boot can automatically identify and load the corresponding environment configuration files.

In Spring Boot, setting yml configuration files in different environments can be achieved through naming rules. The following are configuration file naming rules for development, test, and production environments.
Development environment configuration file:application-{profile}.yml

  • Naming example:application-dev.yml
  • {profile}The part is the environment name, for example: dev, development, etc.

Test environment configuration file:application-{profile}.yml

  • Naming example:application-test.yml
  • {profile}The part is the environment name, for example: test, testing, etc.

Production environment configuration file:application-{profile}.yml

  • Naming example:application-prod.yml
  • {profile}The part is the environment name, for example: prod, production, etc.

According to the above naming rules, when the Spring Boot application is started, the spring.profiles.activecurrently active environment configuration can be specified by setting the property. For example, setting spring.profiles.active=devwill load application-dev.ymlthe configuration from and setting spring.profiles.active=prodwill load application-prod.ymlthe configuration from .

Suppose we have three environments: a development environment, a test environment, and a production environment. We can create the corresponding configuration file as follows :

  1. application-dev.yml: development environment configuration file
  2. application-test.yml: test environment configuration file
  3. application-prod.yml: production environment configuration file

In these configuration files, corresponding configuration items can be set for different environments. For example:

application-dev.yml

app:
  name: My Dev Application

server:
  port: 8080

debug: true

application-test.yml

app:
  name: My Test Application

server:
  port: 8081

debug: true

application-prod.yml

app:
  name: My Production Application

server:
  port: 8082

debug: false

Main configuration file application.yml:

app:
  name: My Application
  version: 1.0.0

spring:
  profiles:
    default: dev

In this way, when starting a Spring Boot application in a different environment, Spring Boot will automatically spring.profiles.activeload the corresponding configuration file according to the value of . For example, when set to , the configuration in devwill be loaded ; when set to , the configuration in will be loaded ; when set to , the configuration in will be loaded.application-dev.ymltestapplication-test.ymlprodapplication- prod.yml

When actually deploying and running the application, you only need to modify spring.profiles.activethe value of to the corresponding environment name, and you can use the corresponding configuration. This method makes the configuration of the application program more flexible and convenient to switch in different environments.

Guess you like

Origin blog.csdn.net/qq_61635026/article/details/132124482