我有课
@Path("/foo")
public class Foo {
public Foo() {
}
public Foo(int n) {
}
@GET
@Produces(MediaType.TEXT_HTML)
@Path("/isAlive")
public String isAlive() {
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/getConfigFromDB")
public Response getConfigFromDB(Request) {
}
假设这是第一次调用这个 web 应用程序,并且必须第一次构造类。如果路径是 "http://localhost/foo/isAlive"
,我可以配置 Jersey 选择第二个构造函数,如果请求路径是 "http://localhost/,我可以配置第一个构造函数吗? foo/getConfigFromDB"
?
最佳答案
您可以自己管理资源实例化,覆盖 Application#getSingletons :
@ApplicationPath("/r")
public class RestApplication extends Application {
@Override
public Set<Object> getSingletons() {
Foo foo = new Foo();
Bar bar = new Bar(42);
return new HashSet<Object>(Arrays.asList(foo, bar));
}
}
但是因此你需要两个类,每个类都有完整路径:
@Path("/foo/isAlive")
public class Foo {
public Foo() {}
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response isAlive() {
return Response.ok("foo is alive").build();
}
}
@Path("/foo/getConfigFromDB")
public class Foo2 {
private int n;
public Foo2(int n) {
this.n = n;
}
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response isAlive() {
return Response.ok("bar initialized with " + n).build();
}
}
你也可以使用 Subresource :
@Path("/foo")
public class Foo {
public Foo() {}
@GET
@Path("/isAlive")
@Produces(MediaType.TEXT_PLAIN)
public Response isAlive() {
return Response.ok("foo is alive").build();
}
@Path("/getConfigFromDB")
@Produces(MediaType.TEXT_PLAIN)
public Bar getConfigFromDB() {
return new Bar(4711);
}
}
public class Bar {
private int n;
public Bar(int n) {
this.n = n;
}
@GET
public Response get() {
return Response.ok("Bar initialized with " + n).build();
}
}
但是,如果您的问题是关于在评论中所写的第二种方法中获取身份验证信息,我无论如何都不会使用构造函数。 参见 this answer其他一些例子。
关于java - Jersey能否根据请求的URI通过特定的构造函数构建资源类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23981411/