4.8.6. 使用 MicroProfile REST 客户端进行上下文依赖项注入
利用 MicroProfile REST 客户端,您必须通过 @RegisterRestClient
类为作为 Jakarta 上下文和依赖项注入(Jakarta 上下文和依赖注入) bean 标注任何接口。例如:
@Path("resource") @RegisterProvider(MyClientResponseFilter.class) public static class TestResourceImpl { @Inject TestDataBase db; @Path("test/{path}") @Consumes("text/plain") @Produces("text/html") @POST public String test(@PathParam("path") String path, @QueryParam("query") String query, String entity) { return db.getByName(query); } } @Path("database") @RegisterRestClient public interface TestDataBase { @Path("") @POST public String getByName(String name); }
此处,MicroProfile REST 客户端实施为 TestDataBase
类服务创建一个客户端,让 TestResourceImpl
类能够轻松访问。但是,它不包括有关 TestDataBase
类实施路径的信息。此信息可以由可选的 @RegisterProvider
参数 baseUri
提供:
@Path("database") @RegisterRestClient(baseUri="https://localhost:8080/webapp") public interface TestDataBase { @Path("") @POST public String getByName(String name); }
这表示您可以访问 TestDataBase 的实现,地址
为 https://localhost:8080/webapp。您还可以使用 MicroProfile 配置在外部提供信息:
<fully qualified name of TestDataBase>/mp-rest/url=<URL>
例如,以下属性表示您可以访问位于 https://localhost:8080/webapp 的 com.bluemondiamond.TestDatabase
类的实施:
com.bluemonkeydiamond.TestDatabase/mp-rest/url=https://localhost:8080/webapp
您可以向 Jakarta Contexts 和 Dependency Injection 客户端提供许多其他属性。例如,com.mycompany.remoteServices.MyServiceClient/mp-rest/providers
,以逗号分隔的完全限定提供程序类名称列表,包含在客户端中。
其他资源
- 如需有关 MicroProfile REST 客户端规范的更多信息,请参阅 MicroProfile 的 Rest 客户端。
- 如需有关 MicroProfile REST 客户端 2.0 功能的更多信息,请参阅 MicroProfile REST 客户端 2.0。