我不知道用@Context注入自定义类实例/ bean的任何方法。我想概述依赖于具体要求的替代方法。
A)完全不需要注射。
使您的自定义上下文成为您的JAX-RS资源类的类成员(而不是每个方法中的局部变量)。容器创建初始化的资源类实例后,利用@PostConstruct实例化自定义上下文。资源类必须是具有请求范围的CDI Bean才能起作用。
@Path("my-service")
@RequestScoped // CDI-bean with request scope only
public class MyResource {
@Context
private HttpServletRequest request;
private MyCustomContext customContext;
@PostConstruct
public void initialize() {
this.customContext = new MyCustomContext(this.request); // request is initialized by the container already at this point
}
@GET
@Path("get-stuff")
@Produces(MediaType.APPLICATION_JSON)
public Response doStuff() {
// ... use the customContext here.
}
}
B)您的自定义上下文仅需要一个HttpServletRequest实例
通过@Context在JAX-RS旁边,通过CDI also provides a predefined bean使用@Inject进行HttpServletRequest。您还可以将自定义上下文设置为CDI-bean,然后注入该预定义的CDI-bean。之后,您可以将自定义上下文注入到JAX-RS资源中(无论它是EJB还是CDI-bean)。
@Dependent // make your custom context a CDI-bean
public class MyCustomContext {
@Inject // inject predefined CDI-bean
private HttpServletRequest request;
}
@Path("my-service")
@RequestScoped // either CDI-bean
//@Stateless // or EJB
public class MyResource {
@Inject // inject custom context via CDI
private MyCustomContext customContext;
@GET
@Path("get-stuff")
@Produces(MediaType.APPLICATION_JSON)
public Response doStuff() {
// ... use the customContext here.
}
}
C)您的自定义上下文需要通过provider specific @Context提供的实例独占权限,例如Request
如果您通过@Context将实例注入到您的非JAX-RS自定义上下文CDI-bean中,它将为 null 。您需要某种机制来从JAX-RS资源中提供注入的实例。在您的自定义上下文中通过@Inject使CDI负责注入,并通过@Produces向您的JAX-RS资源添加生产者方法即可完成工作。
@Dependent // make your custom context a CDI-bean
public class MyCustomContext {
//@Context // in non JAX-RS context the instance will be null
@Inject // instead inject the JAX-RS context instance via CDI
private Request request;
}
@Path("my-service")
@RequestScoped // either CDI-bean
//@Stateless // or EJB
public class MyResource {
@Context // in JAX-RS context the instance will not be null
private Request request;
@Inject
private MyCustomContext customContext;
@Produces // provide the JAX-RS context instance for injection via CDI
@RequestScoped
public Request getContextRequest() {
return this.request;
}
@GET
@Path("get-stuff")
@Produces(MediaType.APPLICATION_JSON)
public Response doStuff() {
// ... use the customContext here.
}
}
本文链接:https://www.f2er.com/3116134.html