專案依賴
專案基於的是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的完整程式碼如下###
@Component public class YamlConfigRefreshPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements EnvironmentAware { private Map> 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 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 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文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JVM通過JavaNativeInterface(JNI)和Java標準庫處理操作系統API差異:1.JNI允許Java代碼調用本地代碼,直接與操作系統API交互。 2.Java標準庫提供統一API,內部映射到不同操作系統API,確保代碼跨平台運行。

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf

javaachievesplatformIndependencEthroughThoJavavIrtualMachine(JVM),wodecutesbytecodeonyanydenanydevicewithajvm.1)javacodeiscompiledintobytecode.2)

JavaGUI開發中的平台獨立性面臨挑戰,但可以通過使用Swing、JavaFX,統一外觀,性能優化,第三方庫和跨平台測試來應對。 JavaGUI開發依賴於AWT和Swing,Swing旨在提供跨平台一致性,但實際效果因操作系統不同而異。解決方案包括:1)使用Swing和JavaFX作為GUI工具包;2)通過UIManager.setLookAndFeel()統一外觀;3)優化性能以適應不同平台;4)使用如ApachePivot或SWT的第三方庫;5)進行跨平台測試以確保一致性。

JavadevelovermentIrelyPlatForm-DeTueTososeVeralFactors.1)JVMVariationsAffectPerformanceNandBehaviorAcroSsdifferentos.2)Nativelibrariesviajnijniiniininiinniinindrododerplatefform.3)

Java代碼在不同平台上運行時會有性能差異。 1)JVM的實現和優化策略不同,如OracleJDK和OpenJDK。 2)操作系統的特性,如內存管理和線程調度,也會影響性能。 3)可以通過選擇合適的JVM、調整JVM參數和代碼優化來提升性能。

Java'splatFormentenceHaslimitations不包括PerformanceOverhead,versionCompatibilityIsissues,挑戰WithnativelibraryIntegration,Platform-SpecificFeatures,andjvminstallation/jvminstallation/jvmintenance/jeartenance.therefactorscomplicatorscomplicatethe“ writeOnce”


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

Dreamweaver CS6
視覺化網頁開發工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

Dreamweaver Mac版
視覺化網頁開發工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!