![](/img/trans.png)
[英]how to change values of Application.properties in Spring
[英]How to change values dynamically in application.properties file in JAVA
我有一个简单的要求,我想在我的 application.properties 文件中设置 rest url
例如
endpoint.some-service.path=http://example.dev
endpoint.some-service.magazines=${endpoint.some-service.path}/api/v1/magazines
endpoint.some-service.magazine=${endpoint.some-service.path}/api/v1/magazines/1234
endpoint.some-service.magazine.articles=${endpoint.some-service.path}/api/v1/magazines/1234/articles
我知道如何通过使用 ENV 变量(例如 http http://example.prod
http://example.dev
http://example.${someenv}
但我不知道如何动态更改1234
或使用从 DB 获得的值。 请帮忙,谢谢
UriComponentsBuilder
和UriComponents
在更改路径变量时很方便。
首先,我们需要将我们的应用程序属性文件更改为
endpoint.some-service.magazine.articles=${endpoint.some-service.path}/api/v1/magazines/**{id}**/articles
在 Java class 中,我们可以使用获取应用程序属性
public class ServiceClient {
@Autowired
private Environment env;
public String getAllArticlesURL() {
env.getProperty("endpoint.some-service.magazine.articles");
}
}
然后我们可以编写 rest 调用
ResponseEntity<String> responseEntity = null;
// URI (URL) parameters
Map<String, String> urlParams = new HashMap<>();
urlParams.put("id, "1234");
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.serviceClient.getAllArticlesURL());
UriComponents uriComponents = builder.buildAndExpand(urlParams).encode();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(headers);
responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.GET, entity, String.class);
希望这个答案可以帮助新蜜蜂:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.