【发布时间】:2016-07-07 10:23:31
【问题描述】:
我有一个 JAX-RS 资源类,它提供到子资源类的路径路由,使用 @Context ResourceContext 为每种资源类型创建子资源实例。在此示例中,我正在实例化一个报告子资源。
资源
@Context
ResourceContext rc;
@Path("reports")
public ReportsResource reportsResource() {
return rc.initResource(new ReportsResource());
}
子资源需要一个 ReportService 类的实例(使用@Stateless 注解定义),自然的解决方案是 @Inject 它...
报告子资源
@Inject
ReportsService rs;
@GET
@Path("{rptno}")
@Produces(MediaType.APPLICATION_XML)
public Report report(@PathParam("rptno") int rptNumber) throws Exception {
return rs.getReport(rptNumber);
}
我在 Glassfish 和 WAS Liberty Profile 中使用 Java EE7 的经验 是没有注入ReportService rs的实例,导致rs为null,导致NPE。
我的假设是,因为资源类正在执行“new ReportsResource()”,CDI 对 ReportsResource 实例没有可见性,因此 ReportsResource 不是容器管理的。 这个好像和这个问题Inject EJB into JAX-RS 2.0 subresource when subresource is got via ResourceContext的情况一样
我的解决方案有些不同,我选择在 Resource 类中@Inject ReportService,然后在 ReportsResource 构造函数上传递实例。
修改后的资源
@Inject
ReportsSerivce rs;
@Context
ResourceContext rc;
@Path("reports")
public ReportsResource reportsResource() {
return rc.initResource(new ReportsResource(rs));
}
修改后的报告子资源
public class ReportsResource {
private ReportsSerivce rs;
public ReportsResource(ReportsSerivce rs) {
this.rs = rs;
}
@Context
HttpHeaders headers;
@GET
@Path("{rptno}")
@Produces(MediaType.APPLICATION_XML)
public Report report(@PathParam("rptno") int rptNumber) throws Exception {
return rs.getReport(rptNumber);
}
所以我的问题
- 我对@Inject 失败原因的假设是否正确?
- 有没有办法让@Inject 在子资源中工作?
- 是否有更好的解决方案将 ReportService 实例从 Resource 传递到更类似于“CDI/Java EE”的 SubResource?
【问题讨论】:
标签: java rest jakarta-ee dependency-injection cdi