紅色部份比較常見,就是讀入 application.properties 裡的資料到 prop 裡,綠色部份是變更想變更的值後在存回去。
Properties prop = new Properties(); URL url = this.getClass().getClassLoader().getResource("application.properties"); URI uri = url.toURI(); File file = new File(uri); InputStream is = new FileInputStream(file); prop.load(is); is.close(); FileOutputStream os = new FileOutputStream(file); prop.setProperty("myKey", myValue); prop.store(os, null); os.close();
因為程式中如果有用到這個 property 檔的相關變數應該也要被更新,在 spring framework 中,載入 property 檔,是在 @Configuration 所在的類別再增加如下註釋。
@PropertySource("classpath:application.properties")
@Value("${myKey}")
private String myValue;
@Inject private StandardEnvironment environment; ... MutablePropertySources propertySources = environment.getPropertySources(); PropertySource resourcePropertySource = propertySources.get("class path resource [application.properties]"); URL url = this.getClass().getClassLoader().getResource("application.properties"); URI uri = url.toURI(); File file = new File(uri); InputStream is = new FileInputStream(file); Properties prop = new Properties(); prop.load(is); is.close(); propertySources.replace("class path resource [application.properties]", new PropertiesPropertySource("class path resource [application.properties]", prop));
沒有留言:
張貼留言