项目依赖项目基于的是2.0.0.release版本,所以snakeyaml需要单独引入,高版本已包含在内
<dependency> <groupid>org.yaml</groupid> <artifactid>snakeyaml</artifactid> <version>1.23</version> </dependency>
网上大多数方法是引入spring-cloud-context配置组件调用contextrefresher的refresh方法达到同样的效果,考虑以下两点未使用
开发框架使用了logback日志,引入spring-cloud-context会造成日志配置读取错误
引入spring-cloud-context会同时引入spring-boot-starter-actuator组件,会开放一些健康检查路由及端口,需要对框架安全方面进行额外控制
yml文件内容获取读取resource文件下的文件需要使用classpathresource获取inputstream
public string gettotalyamlfilecontent() throws exception { string filename = "application.yml"; return getyamlfilecontent(filename); } public string getyamlfilecontent(string filename) throws exception { classpathresource classpathresource = new classpathresource(filename); return onvertstreamtostring(classpathresource.getinputstream()); } public static string convertstreamtostring(inputstream inputstream) throws exception{ return ioutils.tostring(inputstream, "utf-8"); }
yml文件内容更新我们获取到yml文件内容后可视化显示到前台进行展示修改,将修改后的内容通过yaml.load方法转换成map结构,再使用yaml.dumpasmap转换为流写入到文件
public void updatetotalyamlfilecontent(string content) throws exception { string filename = "application.yml"; updateyamlfilecontent(filename, content); } public void updateyamlfilecontent(string filename, string content) throws exception { yaml template = new yaml(); map<string, object> yamlmap = template.load(content); classpathresource classpathresource = new classpathresource(filename); yaml yaml = new yaml(); //字符输出 filewriter filewriter = new filewriter(classpathresource.getfile()); //用yaml方法把map结构格式化为yaml文件结构 filewriter.write(yaml.dumpasmap(yamlmap)); //刷新 filewriter.flush(); //关闭流 filewriter.close(); }
yml属性刷新yml属性在程序中读取使用一般有三种
使用value注解
@value("${system.systemname}") private string systemname;
通过enviroment注入读取
@autowired private environment environment; environment.getproperty("system.systemname")
使用configurationproperties注解读取
@component@configurationproperties(prefix = "system")public class systemconfig { private string systemname;}
property刷新我们通过environment.getproperty方法读取的配置集合实际是存储在propertysources中的,我们只需要把键值对全部取出存储在propertymap中,将更新后的yml文件内容转换成相同格式的ymlmap,两个map进行合并,调用propertysources的replace方法进行整体替换即可
但是yaml.load后的ymlmap和propertysources取出的propertymap两者数据解构是不同的,需要进行手动转换
propertymap集合就是单纯的key,value键值对,key是properties形式的名称,例如system.systemname=>xxxxx集团管理系统
ymlmap集合是key,linkedhashmap的嵌套层次结构,例如system=>(systemname=>xxxxx集团管理系统)
转换方法如下
public hashmap<string, object> convertymlmaptopropertymap(map<string, object> yamlmap) { hashmap<string, object> propertymap = new hashmap<string, object>(); for (string key : yamlmap.keyset()) { string keyname = key; object value = yamlmap.get(key); if (value != null && value.getclass() == linkedhashmap.class) { convertymlmaptopropertymapsub(keyname, ((linkedhashmap<string, object>) value), propertymap); } else { propertymap.put(keyname, value); } } return propertymap; } private void convertymlmaptopropertymapsub(string keyname, linkedhashmap<string, object> submmap, map<string, object> propertymap) { for (string key : submmap.keyset()) { string newkey = keyname + "." + key; object value = submmap.get(key); if (value != null && value.getclass() == linkedhashmap.class) { convertymlmaptopropertymapsub(newkey, ((linkedhashmap<string, object>) value), propertymap); } else { propertymap.put(newkey, value); } } }
刷新方法如下
string name = "applicationconfig: [classpath:/" + filename + "]"; mappropertysource propertysource = (mappropertysource) environment.getpropertysources().get(name); map<string, object> source = propertysource.getsource(); map<string, object> map = new hashmap<>(source.size()); map.putall(source); map<string, object> propertymap = convertymlmaptopropertymap(yamlmap); for (string key : propertymap.keyset()) { object value = propertymap.get(key); map.put(key, value); } environment.getpropertysources().replace(name, new mappropertysource(name, map));
注解刷新不论是value注解还是configurationproperties注解,实际都是通过注入bean对象的属性方法使用的,我们先自定注解refreshvalue来修饰属性所在bean的class
通过实现instantiationawarebeanpostprocessoradapter接口在系统启动时过滤筛选对应的bean存储下来,在更新yml文件时通过spring的event通知更新对应
bean的属性即可
注册事件使用eventlistener注解
@eventlistener public void updateconfig(configupdateevent configupdateevent) { if(mapper.containskey(configupdateevent.key)){ list<fieldpair> fieldpairlist = mapper.get(configupdateevent.key); if(fieldpairlist.size()>0){ for (fieldpair fieldpair:fieldpairlist) { fieldpair.updatevalue(environment); } } } }
通知触发事件使用applicationcontext的publishevent方法
@autowired private applicationcontext applicationcontext; for (string key : propertymap.keyset()) { applicationcontext.publishevent(new yamlconfigrefreshpostprocessor.configupdateevent(this, key)); }
yamlconfigrefreshpostprocessor的完整代码如下
@componentpublic class yamlconfigrefreshpostprocessor extends instantiationawarebeanpostprocessoradapter implements environmentaware { private map<string, list<fieldpair>> mapper = new hashmap<>(); private environment environment; @override public boolean postprocessafterinstantiation(object bean, string beanname) throws beansexception { processmetavalue(bean); return super.postprocessafterinstantiation(bean, beanname); } @override public void setenvironment(environment environment) { this.environment = environment; } private void processmetavalue(object bean) { class clz = bean.getclass(); if (!clz.isannotationpresent(refreshvalue.class)) { return; } if (clz.isannotationpresent(configurationproperties.class)) { //@configurationproperties注解 configurationproperties config = (configurationproperties) clz.getannotation(configurationproperties.class); for (field field : clz.getdeclaredfields()) { string key = config.prefix() + "." + field.getname(); if(mapper.containskey(key)){ mapper.get(key).add(new fieldpair(bean, field, key)); }else{ list<fieldpair> fieldpairlist = new arraylist<>(); fieldpairlist.add(new fieldpair(bean, field, key)); mapper.put(key, fieldpairlist); } } } else { //@valuez注解 try { for (field field : clz.getdeclaredfields()) { if (field.isannotationpresent(value.class)) { value val = field.getannotation(value.class); string key = val.value().replace("${", "").replace("}", ""); if(mapper.containskey(key)){ mapper.get(key).add(new fieldpair(bean, field, key)); }else{ list<fieldpair> fieldpairlist = new arraylist<>(); fieldpairlist.add(new fieldpair(bean, field, key)); mapper.put(key, fieldpairlist); } } } } catch (exception e) { e.printstacktrace(); system.exit(-1); } } } public static class fieldpair { private static propertyplaceholderhelper propertyplaceholderhelper = new propertyplaceholderhelper("${", "}", ":", true); private object bean; private field field; private string value; public fieldpair(object bean, field field, string value) { this.bean = bean; this.field = field; this.value = value; } public void updatevalue(environment environment) { boolean access = field.isaccessible(); if (!access) { field.setaccessible(true); } try { if (field.gettype() == string.class) { string updateval = environment.getproperty(value); field.set(bean, updateval); } else if (field.gettype() == integer.class) { integer updateval = environment.getproperty(value,integer.class); field.set(bean, updateval); } else if (field.gettype() == int.class) { int updateval = environment.getproperty(value,int.class); field.set(bean, updateval); } else if (field.gettype() == boolean.class) { boolean updateval = environment.getproperty(value,boolean.class); field.set(bean, updateval); } else if (field.gettype() == boolean.class) { boolean updateval = environment.getproperty(value,boolean.class); field.set(bean, updateval); } else { string updateval = environment.getproperty(value); field.set(bean, jsonobject.parseobject(updateval, field.gettype())); } } catch (illegalaccessexception e) { e.printstacktrace(); } field.setaccessible(access); } public object getbean() { return bean; } public void setbean(object bean) { this.bean = bean; } public field getfield() { return field; } public void setfield(field field) { this.field = field; } public string getvalue() { return value; } public void setvalue(string value) { this.value = value; } } public static class configupdateevent extends applicationevent { string key; public configupdateevent(object source, string key) { super(source); this.key = key; } } @eventlistener public void updateconfig(configupdateevent configupdateevent) { if(mapper.containskey(configupdateevent.key)){ list<fieldpair> fieldpairlist = mapper.get(configupdateevent.key); if(fieldpairlist.size()>0){ for (fieldpair fieldpair:fieldpairlist) { fieldpair.updatevalue(environment); } } } }}
以上就是springboot怎么动态更新yml文件的详细内容。