Spring Boot EnvironmentPostProcessor 的使用


1、編寫自定義配置文件custom.propertis,並放到resource目錄下

file.size=1111

custom.propertis 文件

2、編寫自定義的加載類CustomEnvironmentPostProcessor,實現EnvironmentPostProcessor接口,重寫postProcessEnvironment方法


package org.yujuan.springbootlearning.processor;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.Properties;

/**
 * The type Custom environment post processor.
 *
 * @author yujuan
 * @time 2019 /08/28 00:36:08
 */
public class CustomEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private final Properties properties = new Properties();
    /**
     * The Profiles.
     */
    private String[] profiles = {
            "custom.properties",
    };

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

        for (String profile : profiles) {
            Resource resource = new ClassPathResource(profile);
            environment.getPropertySources().addLast(loadProfiles(resource));
        }
    }

    private PropertySource<?> loadProfiles(Resource resource) {
        if (!resource.exists()) {
            throw new IllegalArgumentException("file" + resource + "not exist");
        }
        try {
            properties.load(resource.getInputStream());
            return new PropertiesPropertySource(resource.getFilename(), properties);
        } catch (IOException ex) {
            throw new IllegalStateException("load resource exception" + resource, ex);
        }
    }
}

3、在META-INF下創建spring.factories,並且引入CustomEnvironmentPostProcessor 類

org.springframework.boot.env.EnvironmentPostProcessor=org.yujuan.springbootlearning.processor.CustomEnvironmentPostProcessor

spring.factories

4、驗證

通過@value 直接引入或者上下文調用,發現已經獲取到這個配置參數了
驗證結果

歡迎關注博客這個需求做不了

項目地址:github EnvironmentPostProcessor 分支


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM