问题
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.
回答1:
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.
回答2:
Try this one
@Value( "${app.not.found}" )
private String appNotFound;
System.out.println("Message:"+appNotFound);
回答3:
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);
}
}
回答4:
- 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;
}
}
- Then, use this code to get instance of message source which will be bind from AppConfig.java
@Autowired
private MessageSource messageSource;
- String placeDetails =
messageSource.getMessage(code,
`enter code here` Array.Of("pass here value"), new Locale(locale.toLowerCase()));
来源:https://stackoverflow.com/questions/56663736/how-to-set-placeholder-values-in-properties-file-in-spring