background

When we use Spring Boot to package in multiple environments, the configuration properties have different values in different environments, as follows:

spring:
  profiles:
    active: @project.profile@  Configure profiles dynamically according to Maven
---
spring:
  profiles: dev
demo: lengleng_dev
---
spring:
  profiles: prd
demo: lengleng_prd
Copy the code

Or use the Spring Cloud configuration Center (nacOS/Config), etc

The same attribute applied to the configuration may come from configuration files, environment variables, startup parameters, and so on. In many cases, due to the complexity of the configuration above, the application reads the configuration and the value is not the expected value. For example, we want to use the value of the configuration file dev environment, but the value is overwritten by the environment variable or other data.

The solution

Spring Boot 2.3 Provides/Actuator /configprops endpoints (the same endpoints in previous versions, but the behavior is changed/Actuator /env remains the same), and provides tracking of configuration file properties. It is convenient for us to obtain the actual loaded value of the configuration file in real time in spring Boot application.

How to use

  • Importing actuator dependence
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Copy the code
  • exposedconfigpropsThe endpoint
management:
  endpoints:
    web:
      exposure:
        include: 'configprops'
Copy the code
  • Corresponding Configuration Class
@Data
@Component
@ConfigurationProperties("demo")
public class DemoConfig {

    private String username;

    private String password;
}
Copy the code
  • Access the Endpoint to obtain the value of the configuration file in real time

Special instructions

  • The configprops Endpoint desensitizes sensitive fields by default and keyword classes by default
public class Sanitizer {

	private static final String[] REGEX_PARTS = { "*"."$"."^"."+" };

	private static final Set<String> DEFAULT_KEYS_TO_SANITIZE = new LinkedHashSet<>(Arrays.asList("password"."secret"."key"."token".".*credentials.*"."vcap_services"."sun.java.command"));
}
Copy the code
  • Configure a personalized desensitization rule
management:
  endpoint:
    configprops:
      keys-to-sanitize:
        - 'aaa'
        - 'bbb'
Copy the code
  • When an attribute of the configuration class is empty, the attribute is not displayed when accessed through /actuator/configprops.

conclusion

  • Configprops endpoints correspond ConfigurationPropertiesReportEndpoint class, through reading skills can understand from PropertySource access configuration

  • Application scenario: CI should use this endpoint to determine whether the configuration is as expected before executing a unit test to avoid unnecessary execution conditions

  • The above source can be referred to: github.com/lltx/spring…