Springboot 配置文件外置(转载)

776 阅读1分钟

www.cnblogs.com/baoyi/p/spr…

前言:

在springboot项目中,一般的配置文件都在resource/config下面,它可以以两种方式存在,一种是yml,一种是properties方式。

当运维和开发分开的时候,比如连接mysql数据库生产上的时候,运维不会告诉你账户和密码,需要将配置文件放到固定的目录下,运维自己去配置。这样就需要配置文件外置。

当配置文件外置的时候,他是在项目启动的时候,自己去加载配置文件。下面请看实现。

1. 需要增加一个文件

spring.factories,这个文件里面配置启动的时候需要初始化的信息

org.springframework.boot.env.EnvironmentPostProcessor=cn.fintecher.pangolin.service.common.config.AutoConfigEnvironmentPostProcessor

2. 在AutoConfigEnvironmentPostProcessor这个类中增加如下代码

package cn.fintecher.pangolin.service.common.config;import cn.fintecher.pangolin.common.utils.AutoConfigEnvironmentUtil;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.boot.SpringApplication;import org.springframework.boot.env.EnvironmentPostProcessor;import org.springframework.boot.env.PropertySourceLoader;import org.springframework.core.annotation.Order;import org.springframework.core.env.ConfigurableEnvironment;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.core.io.support.ResourcePatternResolver;import org.springframework.core.io.support.SpringFactoriesLoader;import java.util.List;@Order(1)public class AutoConfigEnvironmentPostProcessor implements EnvironmentPostProcessor {    private final Logger logger = LoggerFactory.getLogger(AutoConfigEnvironmentPostProcessor.class);    private final ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();    private final List<PropertySourceLoader> propertySourceLoaders;    public AutoConfigEnvironmentPostProcessor() {        super();        this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, getClass().getClassLoader());    }    @Override    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {        AutoConfigEnvironmentUtil.postProcessEnvironment(environment, application, propertySourceLoaders, resourcePatternResolver, logger);    }}公共方法:

public static void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application,                                   List<PropertySourceLoader> propertySourceLoaders, ResourcePatternResolver resourcePatternResolver,                                   Logger logger) {    String[] activeProfiles = environment.getActiveProfiles();    for (String activeProfile : activeProfiles) {        if (Objects.equals(activeProfile, "swagger"))            continue;        for (PropertySourceLoader loader : propertySourceLoaders) {            for (String fileExtension : loader.getFileExtensions()) {                if (!fileExtension.equals("yml"))                    continue;                String applicationLocal = ResourceUtils.CLASSPATH_URL_PREFIX + "/config/application.yml";                try {                    Resource applicationResource = resourcePatternResolver.getResource(applicationLocal);                    List<PropertySource<?>> applactionYML = loader.load(ResourceUtils.CLASSPATH_URL_PREFIX + "/config/application.yml", applicationResource);                    applactionYML.stream().forEach(environment.getPropertySources()::addLast);                } catch (IOException e) {                    e.printStackTrace();                }                String path = (String) environment.getPropertySources().get("applicationConfig: [classpath:/config/application.yml]").getProperty("spring.config.location");                String location = path + "/application-" + activeProfile + "." + fileExtension;                try {                    Resource[] resources = resourcePatternResolver.getResources(location);                    for (Resource resource : resources) {                        List<PropertySource<?>> propertySources = loader.load(resource.getFilename(), resource);                        if (null != propertySources && !propertySources.isEmpty()) {                            propertySources.stream().forEach(environment.getPropertySources()::addLast);                        }                    }                } catch (IOException e) {                    logger.error(e.getMessage(), e);                }            }        }    }}

3. 在代码中获取了spring.config.location这个配置文件,这个配置文件在application.yml中配置如下

spring:  application:    name: common-service  config:    location: @profile.properties@

@profile.properties@ 取的是pom文件中的<profile.properties>file:d:/tomcat/profiles/${project.artifactId}/properties</profile.properties>

这样这个配置文件就可以放在任何目录下面。

4. 其他信息比如logger日志也需要放在外面,在application.yml增加如下配置即可。

ps: 不需要改动的配置信息都可以配置在application.yml中。

logging:  config: @profile.properties@/logback-spring.xml

5. 可以试试。