首页 > 解决方案 > 如何在 JAVA 的 application.properties 文件中动态更改值

问题描述

我有一个简单的要求,我想在我的 application.properties 文件中设置休息网址

例如

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://example.dev,例如http://example.prodhttp://example.${someenv}

但我不知道如何1234动态更改或使用从 DB 获得的值。请帮忙,谢谢

标签: javaspringspring-boot

解决方案


UriComponentsBuilder并且UriComponents在更改路径变量时很方便。

首先,我们需要将我们的应用程序属性文件更改为

endpoint.some-service.magazine.articles=${endpoint.some-service.path}/api/v1/magazines/**{id}**/articles

在 Java 类中,我们可以使用获取应用程序属性

public class ServiceClient {
    @Autowired
    private Environment env;

    public String getAllArticlesURL() {
        env.getProperty("endpoint.some-service.magazine.articles");
    }
}

然后我们可以编写其余的调用

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

希望这个答案可以帮助新蜜蜂:-)


推荐阅读