java - Quarkus & Microprofile:有没有更好的方法将 application.properties 中的属性用于@ClientHeaderParam?
问题描述
我正在尝试构建一个简单的应用程序,该应用程序使用quarkus-rest-client
. 我必须注入一个 API 密钥作为标头,该标头对于 API 的所有资源都是相同的。所以我想把这个 API Key 的值(取决于环境dev/qa/prod
)放在application.properties
位于src/main/resources
.
我尝试了不同的方法来实现这一点:
- 直接使用
com.acme.Configuration.getKey
到@ClientHeaderParam
value 属性中 - 创建一个 StoresClientHeadersFactory 类,该类实现 ClientHeadersFactory 接口以注入配置
最后,我找到了下面描述的方法来使它工作。
我的问题是:有没有更好的方法呢?
这是我的代码:
- StoreService.java是我访问 API 的客户端
@Path("/stores")
@RegisterRestClient
@ClientHeaderParam(name = "ApiKey", value = "{com.acme.Configuration.getStoresApiKey}")
public interface StoresService {
@GET
@Produces("application/json")
Stores getStores();
}
- 配置.java
@ApplicationScoped
public class Configuration {
@ConfigProperty(name = "apiKey.stores")
private String storesApiKey;
public String getKey() {
return storesApiKey;
}
public static String getStoresApiKey() {
return CDI.current().select(Configuration.class).get().getKey();
}
}
- StoresController.java是 REST 控制器
@Path("/stores")
public class StoresController {
@Inject
@RestClient
StoresService storesService;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Stores getStores() {
return storesService.getStores();
}
}
解决方案
聚会迟到了,但把它放在这里供我自己参考。使用@ClientHeaderParam 和@HeaderParam 似乎有区别,所以我进一步调查了一点:根据Microprofile docs,您可以将计算方法放在花括号中的值。该方法可以提取属性值。
有关更多示例,请参见链接。
编辑:我想出的类似于原来的,但在界面上使用默认方法,所以你至少可以丢弃 Configuration 类。此外,使用 org.eclipse.microprofile.config.Config 和 ConfigProvider 类来获取配置值:
@RegisterRestClient
@ClientHeaderParam(name = "Authorization", value = "{getAuthorizationHeader}")
public interface StoresService {
default String getAuthorizationHeader(){
final Config config = ConfigProvider.getConfig();
return config.getValue("apiKey.stores", String.class);
}
@GET
@Produces("application/json")
Stores getStores();
推荐阅读
- python - 自动选择今天最后创建的文件并发送电子邮件
- amazon-web-services - 如何在启用默认 EBS 加密的情况下使用 Beanstalk?
- c# - 从 Web 项目中排除了一个联系我们的 aspx 页面,但仍收到电子邮件?
- redux - Create-React-App Jest 失败:测试套件必须包含至少一个测试 - 但确实如此
- reactjs - 如何在 React 中动态导入两个 CSS 框架?
- php - 内存限制耗尽flysystem/src/Util/MimeType.php,如何找到文件路径?
- javascript - $refs 会扰乱插值吗?
- python-3.x - Sanic 如何为测试应用加载配置?
- java - 类可以通过接口实现另一个类吗?
- uwp - UWP Win 10 XAML 超级/子脚本呈现问题