繁体   English   中英

如何在 Spring 中更改 Application.properties 的值

[英]how to change values of Application.properties in Spring

有没有办法改变Application.properties中的属性值

例如:

user.update.url = http://localhost:8080/user/{:userId}/update

有没有办法在不使用String.replace()方法的情况下基于{:userId}创建正确的 url?

http://localhost:8080/user/1/update 
http://localhost:8080/user/1/update 
http://localhost:8080/user/1/update 

目前,可怕的实现如下:

应用程序属性:

user.update.url = http://localhost:8080/user/{:userId}/update

A类:

public classs A{

  private int userId;

  @Value("${user.update.url}")
  private String url;

 public A(int userId){
  this.userId=userId
 }

  public String getUrl(){
    return url.replace("{:userId}",userId+"");
  }
}

作为替代方案,您可以使用通常用于解析 i18n 消息的MessageSource

你可以注入它:

@Autowired
private MessageSource messageSource;

然后调用:

messageSource.getMessage(propertyKey, arrayOfParameters, LocaleContextHolder.getLocale());

例如,如果您有以下密钥:

testKey.sample = Hello {0} ! {1}

打电话:

messageSource.getMessage("testKey.sample", "man", "Bye", LocaleContextHolder.getLocale());

将输出消息:

你好男人! 再见

默认情况下,Spring 在src/main/resources文件夹中查找messages.properties文件。 你可以配置它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM