Anjali
Anjali

Reputation: 1691

How to set placeholder values in properties file in spring

Below is application.properties file

app.not.found=app with {0} name can not be found.

How to replace {0} with some value in spring?

I am using below code to read properties file values.

env.getProperty("app.not.found")

but not getting how to set placeholder values.

Upvotes: 5

Views: 8987

Answers (4)

user12428264
user12428264

Reputation: 11

  1. Add this code in in appconfig.java//you can give any file name
@Configuration
public class AppConfig {

    @Bean
    public ResourceBundleMessageSource messageSource() {

        var source = new ResourceBundleMessageSource();
        source.setBasenames("messages/label")//messages is a directory name and label is property file.;
        source.setUseCodeAsDefaultMessage(true);

        return source;
    }
}
  1. Then, use this code to get instance of message source which will be bind from AppConfig.java
@Autowired
private MessageSource messageSource;    
  1. String placeDetails =
messageSource.getMessage(code,
                        `enter code here`    Array.Of("pass here value"), new Locale(locale.toLowerCase()));

Upvotes: 0

eltabo
eltabo

Reputation: 3807

If you can modify your application.properties like that:

app.not.found=app with ${name} name can not be found.

you can use a system property (-Dname=Test) to replace the placeholder:

@SpringBootApplication
public class DemoApplication {


@SpringBootApplication
public class DemoApplication {

    @Value("${app.not.found}")
    private String prop;

    @PostConstruct
    private void pc() {
        System.out.println(prop); //Prints "app with Test name can not be found."
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Upvotes: -1

Nitin Zadage
Nitin Zadage

Reputation: 641

Use MessageFormat.format(String pattern, Object ... arguments). It accepts an array in second parameter, which will replace 0, 1 , 2 ... sequentially.

MessageFormat.format(env.getProperty("app.not.found"), obj)

obj will replace {0} in your string.

Upvotes: 10

Jeya Nandhana
Jeya Nandhana

Reputation: 358

Try this one

@Value( "${app.not.found}" )
private String appNotFound;

System.out.println("Message:"+appNotFound);

Upvotes: 0

Related Questions