The way SpringBoot reads configuration

insert image description here

Several ways to read configuration

Spring Boot provides a variety of ways to read configuration, the following are some of the commonly used ways:

  1. Use the application.properties or application.yml file: In the root directory of the classpath of the Spring Boot project, you can create a file named application.properties or application.yml in which you define configuration properties. Spring Boot automatically loads these files and injects configuration properties into the application. For example, an application.properties file can be defined server.port=8080to specify the application's port.

  2. Use @Value annotation: Use @Value annotation on Spring Boot components (such as classes, fields, parameters) to directly inject the value of the configuration property into the corresponding location. For example, you can @Value("${server.port}")inject the server.port attribute value in the configuration file into the corresponding variable.

  3. Use the @ConfigurationProperties annotation: By creating a @ConfigurationProperties annotation marked Bean, you can bind the value of the configuration property to the property of the Bean. It should be noted that you need to add @Component or @Configuration annotations to the class where the Bean is located to ensure that it is scanned by the Spring container. For example, you can create a Bean named AppConfig, define the fields corresponding to the configuration properties in it, and use the @ConfigurationProperties annotation to specify the prefix, and then inject the Bean into other components that need to use the configuration properties.

  4. Use the Environment object: Through the @Autowired annotation, the Environment object can be injected into any Spring Bean, and then the getProperty method of the object can be used to obtain the value of the configuration property. For example, environment.getProperty("server.port")the server.port property value can be obtained by .

The above are some common methods of Spring Boot reading configuration. According to specific needs and scenarios, you can choose an appropriate way to read and use configuration properties.

How to avoid springboot reading the configuration file multiple times @Value

To avoid Spring Boot reading the values ​​​​in the configuration file multiple times and enhance fault tolerance, annotations can be used @ConfigurationPropertiesinstead of @Valueannotations.

  1. Create a POJO class for mapping configuration properties and @ConfigurationPropertiesmark it with annotations. In this class, define instance variables corresponding to properties in the configuration file, and provide corresponding setter and getter methods.

    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    @Component
    @ConfigurationProperties(prefix = "your.prefix")
    public class AppConfig {
          
          
        private String property1;
        private int property2;
        
        // 省略setter和getter方法
    }
    

    This assumes that the properties in your configuration file are all prefixed with "your.prefix".

  2. Where configuration properties need to be used, AppConfigthe class is introduced through dependency injection and the properties in it are used directly.

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class YourService {
          
          
        private final AppConfig appConfig;
        
        @Autowired
        public YourService(AppConfig appConfig) {
          
          
            this.appConfig = appConfig;
        }
    
        public void someMethod() {
          
          
            // 使用配置属性
            String property1Value = appConfig.getProperty1();
            int property2Value = appConfig.getProperty2();
       
            // 其他操作
        }
    }
    

    To obtain objects through dependency injection AppConfig, you can directly access the corresponding properties in the methods or classes that need to use configuration properties, without using @Valueannotations on each property.

  3. Make sure that the corresponding properties are set correctly in the configuration file for Spring Boot to read.

    your.prefix.property1=value1
    your.prefix.property2=100
    

    In this way, Spring Boot will only read the configuration file once at startup and perform attribute mapping, instead of reading multiple times to cause duplicate attribute values.

Points to note

In the process of using Spring Boot to read the configuration, there are some things to pay attention to as follows:

  1. Naming and location of the configuration file: By default, Spring Boot will automatically load the application.properties or application.yml file in the root directory of the classpath as the configuration file. If you need to change the location or name of the configuration file, you can specify it by using the @PropertySource annotation on the startup class. At the same time, you can also specify the name and location of the configuration file to be loaded through the spring.config.name and spring.config.location properties.

  2. Priority of configuration properties: Spring Boot supports multiple sources of configuration properties (including configuration files, environment variables, command line parameters, etc.), and configuration properties from different sources have different priorities. Typically, command-line arguments have the highest precedence, followed by environment variables, and then properties in configuration files. When multiple sources exist for an attribute with the same name, the later sources will overwrite the previous ones. It is important to note that when using the @ConfigurationProperties annotation to bind properties, the prefix of the property will also affect the priority of the property.

  3. Use type-safe configuration properties: Spring Boot provides type-safe configuration properties. You can create a POJO class and define the fields corresponding to the configuration properties in it, and use the @ConfigurationProperties annotation to specify the prefix to achieve property binding. Doing this avoids hardcoding strings in your code to read properties, increasing type safety and maintainability.

  4. Ensure the correctness of configuration properties: When reading configuration properties, you need to ensure that the values ​​of the properties are legal and correct. Spring Boot provides some validation functions, which can limit the value range or format of attributes by using validation annotations (such as @NotNull, @Min, @Max, etc.) on attribute fields. In addition, more complex verification logic can be implemented through custom validators.

  5. Use Profile for environment switching: Spring Boot supports the use of Profile to achieve configuration switching in different environments. You can specify the currently active Profile through the spring.profiles.active property in the configuration file, and then define the corresponding configuration properties in different configuration files. This makes it easy to manage and switch configurations in different environments.

  6. Security considerations: When reading configuration attributes such as sensitive information or passwords, it is necessary to ensure the security of the configuration. It is recommended to keep sensitive information in a secure location (such as a database, keystore, etc.), and protect the storage and transmission of configuration properties through encryption or other security measures.

The above are some matters that need to be paid attention to when using Spring Boot to read the configuration. Reasonable use of configuration attributes according to specific situations ensures the correctness and security of the application.

How to increase fault tolerance

Here are a few ways to enhance the fault tolerance of Spring Boot's read configuration:

  1. Reasonable configuration file structure: Divide and organize configuration files according to environment, application modules, etc., for easy management and maintenance. For example, you can create different configuration files for different environments and load the corresponding configuration by specifying the active configuration file.

  2. Property Validation and Default Values: Validation and checking of properties before reading configuration properties. Validation and type conversion of properties can be achieved using appropriate annotations such as @Value and @ConfigurationProperties. Also, set default values ​​for properties to prevent exceptions when configuration is missing or wrong.

  3. Exception handling and logging: Appropriate handling and logging of exceptions that may occur during reading configuration. You can use the try-catch block to catch exceptions and record relevant information in time for tracking and troubleshooting.

  4. Multiple configuration sources: In addition to the main configuration file (application.properties or application.yml), additional configuration files or configuration items can be used to override or extend the configuration. For example, you can load additional configuration files using the @PropertySource annotation, or use a distributed configuration solution such as Spring Cloud Config.

  5. Configuration parameter cache: When the application starts, the read configuration parameters are cached in memory to reduce subsequent IO operations for obtaining configurations. You can use the @RefreshScope annotation provided by Spring Boot to implement dynamic refresh of configuration parameters, so that it will take effect in time when the configuration is changed.

  6. Configuration health check: Implement a configuration health check mechanism to ensure the correctness and availability of the configuration. By defining a custom HealthIndicator and adding it to the health check endpoint, the key configuration attributes can be checked and the corresponding health status can be provided.

Please note that the above methods are just some suggestions, and the specific fault tolerance strategy and implementation method depend on specific requirements and project conditions.

Guess you like

Origin blog.csdn.net/weixin_53742691/article/details/131744226