我的应用程序是一个批处理过程,它从 application.properties 文件中提取环境变量。我使用的密码必须每隔几个月更新一次。我想自动化密码更新过程并将更新后的密码保存在属性文件中,以便在将来的运行中使用,但我尝试进行的任何更新都不会传播到 application.config 文件。
当我在 Intellij 中运行时,没有错误,但文件没有更新。当我将应用程序作为 jar 运行时,它给出:
java.io.FileNotFoundException: file:{localpath}\application.jar!\BOOT-INF\classes!\application.properties (The filename, directory name, or volume label syntax is incorrect)
如何动态更新 jar 内的 application.properties 文件,或者当应用程序首次运行时,我是否需要在 jar 外部创建一个新的属性文件?
下面的示例代码片段:
属性.配置:
username=user
password=password123
应用程序.java:
//get properties
prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(f);
// load a properties file
prop.load(input);
} catch (IOException ex) {
logger.error("Error reading application.properties", ex);
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//update properties
prop.setProperty("TESTSTRING", "testvalue");
//write to properties file
OutputStream os = null;
try{
File f = new File(Application.class.getClassLoader().getResource("application.properties").getFile());
os = new FileOutputStream(f);
prop.store(os, comments);
}catch(IOException ex){
logger.error("Error updating application.properties", ex);
ex.printStackTrace();
} finally {
if(os != null){
try{
os.close();
} catch (IOException e){
e.printStackTrace();
}
}
可能会根据运行环境而改变的应用程序的属性应该never被封装在封装组件内。
它不应该硬耦合到组件,并且如果需要,它也应该可以修改,而无需修改打包的组件。
此外,属性可能包含机密信息(如您的情况:用户名和密码)。
所以最好直接存储在目标环境上。
例如,云原生应用程序原则之一Heroku/十二因素 https://12factor.net/config(这通常也是良好的做法)是“将配置存储在环境中”。
因此,出于同样的原因,必须绝对避免更新打包组件内的属性文件。
除此之外,如果发生错误,这会使状态应用程序更难以重现。
对于您的情况,只需填写username
and password
根据目标环境在特定的属性文件中存储属性,并将该文件存储在环境中。
然后您只需通过指定此属性文件来运行应用程序。
例如对于 Windows:
java -jar yourApp-1.0.jar --spring.config.location=file:///D:/application-target-env.properties
这是关于它的参考文档:24.2 访问命令行属性 http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-application-property-files
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)