java - 如何在 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.prod
http://example.${someenv}
但我不知道如何1234
动态更改或使用从 DB 获得的值。请帮忙,谢谢
解决方案
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);
希望这个答案可以帮助新蜜蜂:-)
推荐阅读
- angular - 最终构建中存在哪些角度包
- ios - Xcode 未检测库..在范围内找不到 Firebase 'FaceDetectorOptions'
- terraform - 为什么在使用 terraform 自动缩放时缩放未创建的矩阵?
- firebase - 在 FirebaseFirestore 上为许多用户获取 postId
- php - 在php中显示数组中的第一张图片
- terraform - 使用模块时无法创建 Terraform 资源组
- reactjs - Electron - Webview 必须附加到 DOM 错误
- javascript - 如何在openpgp JS中将参数消息作为文本传递
- settings - 本地管理员行为/权限 windows server 2019 os
- javascript - Discord.js 更改频道权限无济于事