Spring Boot EnvironmentPostProcessor 的使用

Posted jakablog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot EnvironmentPostProcessor 的使用相关的知识,希望对你有一定的参考价值。

1、编写自定义配置文件custom.propertis,并放到resource目录下

file.size=1111

技术图片

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

技术图片

4、验证

通过@value 直接引入或者上下文调用,发现已经获取到这个配置参数了
技术图片

欢迎关注博客这个需求做不了

项目地址:github EnvironmentPostProcessor 分支

以上是关于Spring Boot EnvironmentPostProcessor 的使用的主要内容,如果未能解决你的问题,请参考以下文章

为啥 Spring Boot 应用程序 pom 同时需要 spring-boot-starter-parent 和 spring-boot-starter-web?

《02.Spring Boot连载:Spring Boot实战.Spring Boot核心原理剖析》

spring-boot-quartz, 依赖spring-boot-parent

spring-boot系列:初试spring-boot

Spring Boot:Spring Boot启动原理分析

Spring Boot:Spring Boot启动原理分析