search
HomeJavajavaTutorialHow to use SpringBoot's EnvironmentPostProcessor

How to use SpringBoot's EnvironmentPostProcessor

May 22, 2023 am 09:25 AM
springbootenvironmentpostprocessor

    1. Background

    The Apollo configuration center was used in the previous project. After docking with the Apollo configuration center, the properties of the configuration center are It can be used in the program, so how is this implemented? When were the properties of the configuration center loaded into the program? So if we find out how this is implemented, can we load configuration properties and encryption and decryption functions of configuration properties from anywhere?

    2. Requirements

    How to use SpringBoots EnvironmentPostProcessor

    From the above figure, we know that our requirements are very simple, that is, the attributes we define need to be larger than the configuration file has a higher priority.

    3. Analysis

    1. When to add our own configuration properties to SpringBoot

    When we want to use configuration properties in Bean, then we The configuration properties must be put into Spring Environment before the Bean is instantiated. That is, our interface needs to be called before application context refreshed, and EnvironmentPostProcessor can exactly implement this function.

    2. The priority of obtaining configuration properties

    We know that there is a priority for obtaining properties in Spring.
    For example, we have the following configuration properties username

    ├─application.properties
    │   >> username=huan
    ├─application-dev.properties
    │   >> username=huan.fu

    So what is the value of username at this time? Here is a picture from Apollo to explain this problem.

    Reference link: https://www.apolloconfig.com/#/zh/design/apollo-design

    How to use SpringBoots EnvironmentPostProcessor

    Spring has been added since version 3.1 ConfigurableEnvironment and PropertySource:

    ConfigurableEnvironment
    • Spring’s ApplicationContext will contain an Environment (implementing the ConfigurableEnvironment interface)

    • ConfigurableEnvironment itself contains many PropertySource

    PropertySource

    • Property Source

    • can be understood as many Key-Value attribute configurations

    As can be seen from the schematic diagram above, key appears at the very beginning The priority in PropertySource is higher. In the above example, the value of username in SpringBoot is huan.fu.

    3. When to add our own configuration

    From the second stepGet the priority of the configuration attribute It can be seen that the higher the PropertySource is, the higher Execute it first, then for our configuration to take effect, it must be placed as early as possible.

    How to use SpringBoots EnvironmentPostProcessor

    As can be seen from the above figure, SpringBoot loads various configurations through EnvironmentPostProcessor, and the specific implementation is ConfigDataEnvironmentPostProcessor to achieve. Then we write an implementation class of EnvironmentPostProcessor ourselves, then execute it after ConfigDataEnvironmentPostProcessor, and add it to the first position in Environment.

    How to use SpringBoots EnvironmentPostProcessor

    4. Implementation

    1. Introduce SpringBoot dependency

    <?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.6.6</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.huan.springcloud</groupId>
        <artifactId>springboot-extension-point</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>springboot-extension-point</name>
        <properties>
            <java.version>1.8</java.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        </dependencies>
    </project>

    2. Configure properties in application.properties

    vim application.properties
    username=huan

    3. Write custom attributes and add them to Spring Environment

    How to use SpringBoots EnvironmentPostProcessor

    Note:
    1. If you find that there is no log output in the program, check whether is used slf4jOutput log. At this time, the log cannot be output because the log system has not been initialized. The solution is as follows:

    SpringBoot版本
    		>= 2.4 可以参考上图中的使用 DeferredLogFactory 来输出日志
    		< 2.4
    			1、参考如下链接 https://stackoverflow.com/questions/42839798/how-to-log-errors-in-a-environmentpostprocessor-execution
    			2、核心代码:
    				@Component
    				public class MyEnvironmentPostProcessor implements
    				        EnvironmentPostProcessor, ApplicationListener<ApplicationEvent> {
    				    private static final DeferredLog log = new DeferredLog();
    				    @Override
    				    public void postProcessEnvironment(
    				            ConfigurableEnvironment env, SpringApplication app) {
    				        log.error("This should be printed");
    				    }
    				    @Override
    				    public void onApplicationEvent(ApplicationEvent event) {
    				        log.replayTo(MyEnvironmentPostProcessor.class);
    				    }
    				}

    4. Make the customized configuration take effect through SPI

    1. Create a new# under src/main/resources ##META-INF/spring.factoriesFile

    How to use SpringBoots EnvironmentPostProcessor

    2. Configuration

    org.springframework.boot.env.EnvironmentPostProcessor=\
      com.huan.springcloud.extensionpoint.environmentpostprocessor.CustomEnvironmentPostProcessor

    5. Write a test class and output the defined username attribute Value

    @Component
    public class PrintCustomizeEnvironmentProperty implements ApplicationRunner {
    
        private static final Logger log = LoggerFactory.getLogger(PrintCustomizeEnvironmentProperty.class);
        @Value("${username}")
        private String userName;
        @Override
        public void run(ApplicationArguments args) {
            log.info("获取到的 username 的属性值为: {}", userName);
        }
    }

    6. Running result

    How to use SpringBoots EnvironmentPostProcessor

    5. Notes

    1. The log cannot be output

    Refer to the above ’

    3. Write custom properties and add the solution provided by in Spring Environment.

    2. Check that the configuration does not take effect

    • Check the priority of EnvironmentPostProcessor to see if the priority value returned by @Order or Ordered is incorrect.

    • 看看别的地方是否实现了 EnvironmentPostProcessor或ApplicationContextInitializer或BeanFactoryPostProcessor或BeanDefinitionRegistryPostProcessor等这些接口,在这个里面修改了 PropertySource的顺序。

    • 理解 Spring 获取获取属性的顺序 参考 2、获取配置属性的优先级

    3、日志系统如何初始化

    如下代码初始化日志系统

    org.springframework.boot.context.logging.LoggingApplicationListener

    The above is the detailed content of How to use SpringBoot's EnvironmentPostProcessor. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

    Start Spring using IntelliJIDEAUltimate version...

    How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

    When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

    How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

    How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

    How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

    Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

    How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

    Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

    E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

    Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

    How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

    How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.