spring—更改从属性文件读取的属性值的最佳方法

6za6bjd0  于 2021-07-16  发布在  Java
关注(0)|答案(2)|浏览(307)

我有一个 application.properties 文件如下

mail.content = Hey #name Good morning #name, are you a good developer?

我的javaspring启动代码

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方法。我只想知道还有比这更好的办法吗?如果可能的话,请帮助我做那件事?
谢谢您

njthzxwz

njthzxwz1#

看看java的messageformat并使用该语法。比“全部替换”功能更强大,副作用更少。
https://docs.oracle.com/javase/1.5.0/docs/api/java/text/messageformat.html
在application.properties中使用{}占位符。
int行星=7;string event=“原力中的干扰”;

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.
q7solyqu

q7solyqu2#

我会在创建mailutils时更改属性。“名字”在哪里声明?

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(){
        ...
    }
}

相关问题