配置文件放到war包或者jar包是一件很被动的事,弄不好就得重新打包,然后重新上线。这就很麻烦,办法肯定是有的。这里就介绍一下PropertySourcesPlaceholderConfigurer类,这个类,先看一下这个类。EnvironmentAware是用来获取环境变量配置的存储地。
大概知道这块是先拿到的系统变量,然后拿本地变量。
在获取本地变量的的时候 this.loadProperties(result);使用方法,然后result用来装载加载完毕的配置信息。最后将配置信息返回去。我们跟踪一下loadProperties方法在父类PropertiesLoaderSupport中。继续追踪发现这块默认的读取locations文件地址然后自动装配。
因此我们创建本地测试配置文件lishi.txt,然后debug测试一下。发现父类方法自动加载了配置,我们自定义加载配置功能也实现了。
采用locations的方式使用默认父类配置读取配置和自定义加载文件系统配置。
通过上述描述,我们基本实现了配置文件的外提,这样我们就可以随意修改配置文件而不需要重新打包了,感觉挺给力的。这块最好的一点是我们完全可以将这里读取文件系统的配置文件改成从其他系统中获取呀,对,这就是配置中心。
解决了配置的非内部性,我们就要研究一下配置的加载问题了。其实配置的热加载就比较简单了,因为配置都是在一个bean里的,我们直接用set方法就行,当检测到配置产生变动,那么我们就直接将配置拉过来然后保存到本地,然后发送一个事件将配置变动的消息广播出去,然后让用到该配置的bean去从本地获取配置就可以了。
贴一下今天的代码
@Component
public class MyPropertySourcesPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer {
/**
* 加载本地配置文件
*/
private String configPath="C:\\Users\\tianjingle\\Desktop\\tianjingle.txt";
private String configPath1="C:\\Users\\tianjingle\\Desktop\\lishi.txt";
/**
* *这里重新加载
* @param props 元素
* @throws IOException 异常
*/
protected void loadProperties(Properties props) throws IOException {
//这里设置一个配置文件
Resource myresource=new FileSystemResource(configPath1);
this.setLocations(myresource);
super.loadProperties(props);
//这里自定义加载文件
if (StringUtils.hasText(configPath)) {
Map myconfig=new HashMap<>();
File file = new File(configPath);
List list = FileUtils.readLines(file, StandardCharsets.UTF_8);
list.forEach(c->{
String[] properties=c.split("=");
myconfig.put(properties[0],properties[1]);
});
props.putAll(myconfig);
}
}
}
启动类
@RestController
@SpringBootApplication
public class Demo1Application implements EnvironmentAware {
@Value("${test}")
private String test;
@Value("${env}")
private String myenv;
private static Environment env;
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
System.out.println(env.toString());
}
@GetMapping(value = "/test")
public String test(){
return test+"-"+myenv+"{"+this.env+"}";
}
@Override
public void setEnvironment(Environment environment) {
this.env=environment;
}
}
晚安,早睡早起~
更多推荐