springboot下自定義讀取任意位置的配置文件


import org.apache.commons.lang3.StringUtils;
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.FileSystemResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.Assert;
import java.io.File;
import java.io.IOException;
import java.util.Properties;

/**
 * @Description 自定義配置文件路徑加載
 * @Date 2019/12/08 2·:40
 * @author 楊光
 */
public class ConfEnvironmentPostProcessor implements EnvironmentPostProcessor {
    /**
     * 配置文件的絕對路徑
     */
    private static final String PROFILES_CONF_PATH = "properties.path";
    /**
     * 無特殊要求 但不能爲空或null
     */
    private static final String MAP_KEY = "application.properties";

    /**
     * @Description 加載配置文件方法
     */
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    	  try{
    		  //從默認配置文件中獲得外部文件路徑
            String rootPath = environment.getProperty(PROFILES_CONF_PATH);
            Assert.hasText(rootPath, "外部配置文件路徑不能爲空");
             MutablePropertySources propertySources = environment.getPropertySources();
            File defaultFile = new File(rootPath);
            Assert.isTrue(defaultFile.exists(),"外部配置文件不存在"+rootPath);
			Properties defaultProperties = loadProperties(defaultFile);
			//加入
			propertySources.addFirst(new PropertiesPropertySource(MAP_KEY, defaultProperties));
			System.out.println("加載配置文件:" + rootPath);
        }  catch (IOException e){
            e.printStackTrace();
            Assert.isTrue(false,"文件讀取錯誤"+e.getMessage());
        }
    }
    /**
     * @Description 加載配置文件
     */
    private Properties loadProperties(File f) throws IOException{
        FileSystemResource resource = new FileSystemResource(f);
        return PropertiesLoaderUtils.loadProperties(resource);
    }
   
}

 2.在resources下加入包META-INF/spring.factories

org.springframework.boot.env.EnvironmentPostProcessor=com.eca.mind.bmw.ConfEnvironmentPostProcessor

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章