spring boot在tomcat运行多环境配置分离方案

在resources/META-INF目录下新建 spring.factories

内容:

org.springframework.boot.env.EnvironmentPostProcessor=com.testproject.system.config.LocalSettingsEnvironmentPostProcessor

LocalSettingsEnvironmentPostProcessor.java内容

import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

/**
 * tomcat war配置分离,使用外部application.properties的关键操作,同时要在resources下新建 META-INF/spring.factories
 * 内容为org.springframework.boot.env.EnvironmentPostProcessor=com.feiniu.ssologin.system.config.LocalSettingsEnvironmentPostProcessor
 * 配置后会在项目启动之初执行 SpringApplicationBuilder.profiles()配置时已经启动执行,故不能达到效果
 *
 * @author sean
 */
public class LocalSettingsEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private static final String LOCATION_SERVER = "/home/webdata/projectName/webroot/config/application.properties";
    private static final String LOCATION_LOCATION = "/application-location.properties";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
        MutablePropertySources propertySources = configurableEnvironment.getPropertySources();
//            System.out.println("Loading local settings from " + file.getAbsolutePath());
        Properties properties = loadProperties();
//            System.out.println(properties.toString());
        propertySources.addFirst(new PropertiesPropertySource("Config", properties));
    }

    private Properties loadProperties() {
        File file = new File(LOCATION_SERVER);
        if (file.exists()) {
            return loadFileProperties(file);
        } else {
            return loadClassPathProperties(LOCATION_LOCATION);
        }
    }

    private Properties loadFileProperties(File f) {

        FileSystemResource resource = new FileSystemResource(f);
        try {
            return PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException ex) {
            throw new IllegalStateException("Failed to load local settings from " + f.getAbsolutePath(), ex);
        }
    }

    private Properties loadClassPathProperties(String path) {
        ClassPathResource resource = new ClassPathResource(path);
        try {
            return PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException ex) {
            throw new IllegalStateException("Failed to load local settings from " + LOCATION_LOCATION, ex);
        }
    }
}
原文地址:https://www.cnblogs.com/seans/p/9540438.html