Reputation: 1691
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
Reputation: 11
@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;
}
}
@Autowired
private MessageSource messageSource;
messageSource.getMessage(code,
`enter code here` Array.Of("pass here value"), new Locale(locale.toLowerCase()));
Upvotes: 0
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
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
Reputation: 358
Try this one
@Value( "${app.not.found}" )
private String appNotFound;
System.out.println("Message:"+appNotFound);
Upvotes: 0