之前一直都是将配置文件等全部打成一个包使用,后来因为维护啥的都比较困难,所以将配置文件移出来,从外界去依赖:
首先就是在项目的 configuration文件夹中添加一个类: LocalSettingsEnvironmentPostProcessor( configuration:用于存储各种SpringBoot的配置文件)
package com.altynai.xxxxxx.configuration;
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 java.io.File;
import java.io.IOException;
import java.util.Properties;
public class LocalSettingsEnvironmentPostProcessor implements EnvironmentPostProcessor{
private static final String LOCATION = "D:\\idea\\application.properties";
@Override
public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
File file = new File(LOCATION);
// File file = new File(System.getProperty("user.home"), LOCATION);
// System.out.println("user.home" + System.getProperty("user.home"));
if (file.exists()) {
MutablePropertySources propertySources = configurableEnvironment.getPropertySources();
// System.out.println("Loading local settings from " + file.getAbsolutePath());
Properties properties = loadProperties(file);
// System.out.println(properties.toString());
propertySources.addFirst(new PropertiesPropertySource("Config", properties));
}
}
private Properties loadProperties(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);
}
}
}
这个java类的作用就是根据指定的配置文件路径,读取文件,添加到程序运行的环境中。注意,根据我的测试,这里导入的外部配置文件只能是.properties的文件,如果是.yml的话会有问题。
然后在你的resources文件夹下创建一个文件夹名为META-INF,在里面创建一个spring.factories的文件,文件内容如下:
org.springframework.boot.env.EnvironmentPostProcessor=com.shop.xxxxx.configuration.LocalSettingsEnvironmentPostProcessor
这个文件的作用就是设置SpringBoot服务启动的时候调用我们刚才写的那个Java类。
这里还需要说明的是假设你原本的配置文件的设置属性与导入了外部配置文件的设置属性重复了最终系统运行起来使用的是哪一个?
答案是,看两个配置文件加入程序环境的先后顺序,后面的会覆盖前面的。
上面的Java类中有这个一段代码,这里的意思就是,外部的文件是最先导入的。
propertySources.addFirst(new PropertiesPropertySource("Config", properties));
如果设置为下面的这个
propertySources.addLast(new PropertiesPropertySource("Config", properties));
则表示最后导入外部配置文件。