How to set placeholder values in properties file in spring

不问归期 提交于 2021-02-10 07:40:43

问题


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:


  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()));


来源:https://stackoverflow.com/questions/56663736/how-to-set-placeholder-values-in-properties-file-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!