我有一个application.properties
文件,如下所示
mail.content = Hey #name Good morning #name, are you a good developer?
我的Java Spring启动代码
public class MailUtils{
@Value("${mail.content}")
String content;
//Other codes
public void sendMail(){
//Other code
String body = content.replaceAll("#name", firstName);
//reamining code
}
我需要根据java变量更改应用程序属性中的值。为此,我使用了String类replace方法。我只想知道我们还有比这更好的方法吗?如果可能的话,请帮我做这件事?
谢谢
看看Java的MessageFormat并使用该语法。比全部替代更强大,副作用更少。
https://docs.oracle.com/javase/1.5.0/docs/api/java/text/MessageFormat.html
在application.properties中使用{}占位符。
int行星=7;字符串事件=";警队的干扰";;
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
planet, new Date(), event);
The output is:
At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.
我会在创建MailUtils时更改属性。"firstName"在哪里声明?
public class MailUtils {
String content;
@Value("${mail.content}")
public void setContent(String content) {
String firstname = System.getProperty("user.name");
this.content = content.replace("#name", firstname);
}
public void sendMail(){
...
}
}