首页 > 解决方案 > Quarkus & Microprofile:有没有更好的方法将 application.properties 中的属性用于@ClientHeaderParam?

问题描述

我正在尝试构建一个简单的应用程序,该应用程序使用quarkus-rest-client. 我必须注入一个 API 密钥作为标头,该标头对于 API 的所有资源都是相同的。所以我想把这个 API Key 的值(取决于环境dev/qa/prod)放在application.properties位于src/main/resources.

我尝试了不同的方法来实现这一点:

最后,我找到了下面描述的方法来使它工作。

我的问题是:有没有更好的方法呢?

这是我的代码:

@Path("/stores")
@RegisterRestClient
@ClientHeaderParam(name = "ApiKey", value = "{com.acme.Configuration.getStoresApiKey}")
public interface StoresService {

    @GET
    @Produces("application/json")
    Stores getStores();

}
@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();
    }

}
@Path("/stores")
public class StoresController {

    @Inject
    @RestClient
    StoresService storesService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Stores getStores() {
        return storesService.getStores();
    }

}

标签: javaclientquarkusmicroprofile

解决方案


聚会迟到了,但把它放在这里供我自己参考。使用@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();


推荐阅读