例如,我们有一些带有子资源的 java-ws rs 结构:
@Stateless
@Path("/rootpath/")
class Root {
@Path("/A")
public A getA {
...
}
@Path("/B")
public B getB {
...
}
}
@Stateless
@LocalBean
class A {
@GET
@Path("/getAStuff")
public String getAStuff(
@QueryParam("p") callback: String) {
return "A stuff";
}
@GET
@Path("/getAnotherAStuff")
public String getOtherStuff(
@QueryParam("p") callback: String) {
return "A stuff";
}
}
@Stateless
@LocalBean
class B {
@GET
@Path("/getBStuff")
public String getBStuff(
@QueryParam("p") callback: String) {
return "B stuff";
}
}
这个结构实际上要复杂得多(更广、更深)。问题是 - getA 和 getB 实现的最佳方式是什么?
我可以做到这一点:
public A getA {
return new A();
}
或者我可以使用 EJB:
@EJB
A a;
public A getA {
return a;
}
或者那样:
@Context
private ResourceContext resourceContext;
public A getA {
A a = resourceContext.getResource(A.class);
return a;
}
第一种方法使我可以读取 Root 类中的 p 参数,然后通过构造函数参数将其传递给 A 和 B,而无需在 A 和 B 的每个方法中使用它。但是 Java EE 教程说我应该为 Web 服务使用无状态 EJB类。
最佳答案
首先,永远不要自己构建 EJB - 您手头有一个容器,它负责组件的生命周期。
其次,由于我假设您至少使用 Java EE 6,因此请对组件使用常见的 @Inject
。
第三,您不必使用 EJB,它也可以是 CDI 组件或普通 POJO。
最后,我不明白,为什么在 Root
中为类 A
和 B
提供 getter? @Path
注释也可以位于您的类声明本身上。
关于Java-WS RS资源结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24429556/