【发布时间】:2016-08-21 19:27:59
【问题描述】:
我需要将UriInfo 注入客户端,但找不到解决方案。
主要目标是在创建 WebTarget 时获取基本 URI (localhost:port)。事实上,应用程序被不同的 Web 客户端使用,并且需要显式 URI。此外,我想测试客户端资源通信,因此我也需要在我的测试类中获得严格的 URI。
应用程序是多模块 Maven 项目。资源和客户端位于不同的模块中。
为了清楚起见,我在下面描述了项目结构(请不要注意文件夹结构 - 它以简单的形式描述):
--service-module
\Resource.java
\web.xml
--client-module
\Client.java
--client-test-module
\ClientResourceIntegrationTest.java
Client.java
public class Client {
@Context
UriInfo uriInfo;
public Result getResult(String userName, Filter queryFilter) {
ClientConfig clientConfig = new ClientConfig();
clientConfig.register(Filter.class);
Client client = ClientBuilder.newClient(clientConfig);
WebTarget webTarget = client
//need to change on dynamically retrieved URI
.target("http://localhost:1234/")
.path("all/")
.path(userName);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.post(Entity.entity(queryFilter, MediaType.APPLICATION_JSON));
int responseStatus = response.getStatus();
Result queryResult = response.readEntity(Result.class);
response.close();
return queryResult;
}
}
Resource.java
@Path("/")
public class Resource {
@Context
UriInfo uriInfo;
@POST
@Path("all/{user}")
@Produces(MediaType.APPLICATION_JSON)
public Result getAll(@PathParam("user") String userName, Filter filter) {
List<Map<String, Object>> attributes = new ArrayList<Map<String, Object>>();
Map<String, Object> values = new HashMap<String, Object>();
values.put("value", 1);
attributes.add(values);
Result result = new Result(attributes);
return result;
}
}
Jersey 的 ServletContainer 定义在 web.xml 中,位于 service-module 中。扫描的包只是位于该模块中的资源(因此UriInfo 被注入到资源对象中)。其余类的实例(包括客户端)是在没有 IoC 容器的情况下创建的(显然UriInfo 为空)。所以,我不知道在这种情况下如何获取 URI。如果您对在哪里阅读或什至如何阅读有任何建议 - 请发表评论。
【问题讨论】:
标签: java jersey-2.0 jersey-client