Spring使用EnvironmentPostProcessor自定义启动配置项

EnvironmentPostProcessor

使用该接口可以在项目启动时,修改或者添加一些自定义的环境配置;

Environment

spring中对环境的抽象(包含环境变量,系统信息以及用户信息),可以使用ApplicationContext.getEnvironment();获取到。使用Environment.getProperty(“key”),获取环境变量。
但一般情况下很少直接使用Environment,在日常的SpringBoot编程中会使用到@Value("${}")来获取到环境变量里的值;
还可以通过Environment.getActiveProfiles()获取当前的环境Profile

PropertySource

spring中对属性的抽象,可以使用该接口的实现自定义一些环境属性变量,通过 Environment.getPropertySources().addFirst(PropertySource);或者 Environment.getPropertySources().addLast(PropertySource);当使用addBefore()时添加的环境属性优先级高,当和已经有的环境变量重复时,会覆盖已经有的环境变量。相反,会被已经有的环境变量覆盖;
另外还有addBefore(String relativePropertySourceName,PropertySource propertySource); addAfter(String relativePropertySourceName,PropertySource propertySource);

PropertySourceLoader

当要添加的属性变量在配置文件中时,可以使用PropertySourceLoader.load(String name,Resource resource);获取List(PropertySource);
实现类有:
YamlPropertySourceLoader;
PropertiesPropertySourceLoader;

Resource

spring 对资源的抽象;实现类有:

  • ClassPathResource (常用)
  • ServletContextResource
  • UrlResource

示例代码:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.IOException;

public class CustomEnvironmentConfig implements EnvironmentPostProcessor {
    
    private static Logger log = LoggerFactory.getLogger(CustomEnvironmentConfig.class);
    private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    private static final String YML_FILE_NAME = "routerAdapter";
    private static final String YML_FILE_TYPE = "yml";
    private static final String YML_FILE_PATH = "config/";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        String sourcePath = YML_FILE_PATH + YML_FILE_NAME + "." + YML_FILE_TYPE;
        log.info(sourcePath);
        String sourceName = YML_FILE_NAME;
        Resource resource = new ClassPathResource(sourcePath);
        PropertySource<?> propertySource = null;
        if(resource.exists()) {
            try {
                propertySource = this.loader.load(sourceName,resource).get(0);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        environment.getPropertySources().addLast(propertySource);
        
        String[] activeProfiles = environment.getActiveProfiles();
        String active = activeProfiles[0];
        String activeSourcePath = YML_FILE_PATH + YML_FILE_NAME + "-" + active + "." + YML_FILE_TYPE;
        String activeSourceName = YML_FILE_NAME + "-" + active;
        Resource activeResource = new ClassPathResource(activeSourcePath);
        PropertySource<?> activePropertySource = null;
        if(resource.exists()) {
            try {
                activePropertySource = this.loader.load(activeSourceName,activeResource).get(0);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        environment.getPropertySources().addBefore(propertySource.getName(),activePropertySource);
    }
}

进行配置

写完配置类后并不能直接生效,需要进行下一步的配置:
在META-INF的spring.factories中添加

org.springframework.boot.env.EnvironmentPostProcessor=\
com.cheng.boot.config.CustomEnvironmentConfig

你可能感兴趣的:(spring,java,spring)