Search code examples
springstringspring-bootjava-8application.properties

Best way to alter the property value which is read from the properties files


I have an application.properties file as follow

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

My Java Spring boot code

public class MailUtils{
     @Value("${mail.content}")
     String content;
     //Other codes
    
    public void sendMail(){
     //Other code
     String body = content.replaceAll("#name", firstName);
     //reamining code
}

I need to alter the value from the application properties based on the java variable. For that, I am using the String class replace method. I just need to know do we have any way better than this? If it is possible, kindly assist me to do that?

Thank you


Solution

  • Take a look at Java’s MessageFormat and use that syntax. Much more powerful and less side effects than a replace all.

    https://docs.oracle.com/javase/1.5.0/docs/api/java/text/MessageFormat.html

    Use the {} placeholder in your application.properties.

    int planet = 7; String event = "a disturbance in the Force";

    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.