在一个springboot的项目中创建一个加载资源的类
LoadPropertiesConfig
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.slf4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
public class LoadPropertiesConfig implements EnvironmentPostProcessor, Ordered {
private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(LoadPropertiesConfig.class);
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
//此处可以http方式 到配置服务器拉取一堆公共配置+本项目个性配置的json串,拼到Properties里
Properties properties = new Properties();
try {
properties.load(
new FileInputStream(new File("D:\\service\\demo-parents\\springboot-app\\application.properties")));
} catch (FileNotFoundException e) {
LOG.error("error message", e);
} catch (IOException e) {
LOG.error("error message", e);
}
MutablePropertySources propertySources = environment.getPropertySources();
//addLast 结合下面的 getOrder() 保证顺序 读者也可以试试其他姿势的加载顺序
propertySources.addLast(new PropertiesPropertySource("thirdEnv", properties));
}
@Override
public int getOrder() {
// +1 保证application.propertie里的内容能覆盖掉本配置文件中默认的
// 如果不想被覆盖 可以去掉 +1 或者 -1 试试
return Integer.MIN_VALUE;
}
}
这样就实现了用远程资源覆盖本地资源的情况
测试代码
@SpringBootApplication
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 类PropertiesCheckController.java的实现描述:验证自定义配置文件
*
* @author xupeng 2017年3月16日 下午4:04:24
*/
@RestController
public class PropertiesCheckController {
@Value("${name}")
private String name;
@RequestMapping("/showName")
public String showName() {
return name;
}
}
本地配置文件
name=ceshi
远程配置文件
name=name
用以上代码测试,当没有加载到远程资源的时候访问showName
返回的是ceshi当资源被覆盖之后就会显示name