春季如何在属性文件中设置占位符值

时间:2019-06-19 08:54:01

标签: java spring spring-boot spring-mvc spring-data-jpa

下面是application.properties文件

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

如何在春季用一些值替换{0}?

我正在使用以下代码读取属性文件值。

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

但未获得设置占位符值的方法。

4 个答案:

答案 0 :(得分:2)

使用MessageFormat.format(String pattern, Object ... arguments)。它在第二个参数中接受一个数组,该数组将顺序替换0、1、2...。

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

obj将替换您字符串中的{0}。

答案 1 :(得分:1)

尝试这个

kubectl create -f template.yml

答案 2 :(得分:0)

如果您可以像这样修改application.properties:

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

您可以使用系统属性(-Dname = Test)替换占位符:

@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);
    }
}

答案 3 :(得分:0)

  1. 在appconfig.java中添加此代码///您可以指定任何文件名
docker run -it --rm --name project_run project
  1. 然后,使用此代码获取将从AppConfig.java绑定的消息源实例。
@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. 字符串placeDetails =
@Autowired
private MessageSource messageSource;    
相关问题