问题
I would like to implement a REST API using Jersey 2 and I would like to have resources separated into interfaces and their implementations like e.g.:
@Path("hello")
public interface HelloLogic {
@GET
@Produces("application/json")
public String hello();
}
public class HelloLogicResource implements HelloLogic {
public String hello() {
return "{\"reply\": \"Hello\"}";
}
}
I do not have any luck getting the resources exposed though. For the hello resource just mentioned I was hoping that the following would be enough:
public class MyApplication extends ResourceConfig {
public MyApplication() {
register(new MyApplicationBinder());
}
}
public class MyApplicationBinder extends AbstractBinder {
@Override
protected void configure() {
bind(HelloLogic.class).to(HelloLogicResource.class);
}
}
web.xml:
<servlet>
<servlet-name>MyApplication</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>stines.api.MyApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyApplication</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
pom.xml:
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.4.1</version>
</dependency>
But when hitting
http://localhost:8080/hello
I get a 404 response:
Input will be greatly appreciated :) Thanks.
New discovery: it works with this:
public class MyApplication extends ResourceConfig {
public MyApplication() {
registerClasses(HelloLogicResource.class);
}
}
回答1:
Edit 1: You need to tell Jersey where your resources are:
public MyApplication() {
packages("stines.api.resources");
register(new MyApplicationBinder());
}
I believe in this case you want to use the package where HelloLogic lives, but you can also add multiple packages if needed:
public MyApplication() {
packages("stines.api.resources;stines.api.resources.impl");
register(new MyApplicationBinder());
}
Edit 2: removed note about backwards Guice binding
回答2:
This works:
public class MyApplication extends ResourceConfig {
public MyApplication() {
registerClasses(HelloLogicResource.class);
}
}
来源:https://stackoverflow.com/questions/20564142/rest-api-using-jersey-2