如何在JAVA中动态更改application.properties文件中的值



我有一个简单的要求,我想在我的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://example.dev更改为http://example.prod,例如http://example.${someenv}

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

UriComponentsBuilderUriComponents在更改路径变量时非常方便。

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

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

希望这个答案能帮助新蜜蜂:-(

最新更新