我想使用 Jersey 2 实现 REST API,并且我希望将资源分为接口(interface)及其实现,例如:
@Path("hello")
public interface HelloLogic {
@GET
@Produces("application/json")
public String hello();
}
public class HelloLogicResource implements HelloLogic {
public String hello() {
return "{\"reply\": \"Hello\"}";
}
}
不过,我没有运气获得资源。对于刚刚提到的 hello 资源,我希望以下内容就足够了:
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>
但是当击中
http://localhost:8080/hello
我收到 404 响应:
我们将不胜感激:)谢谢。
新发现:它适用于此:
public class MyApplication extends ResourceConfig {
public MyApplication() {
registerClasses(HelloLogicResource.class);
}
}
最佳答案
编辑 1:您需要告诉 Jersey 您的资源在哪里:
public MyApplication() {
packages("stines.api.resources");
register(new MyApplicationBinder());
}
我相信在这种情况下您想要使用 HelloLogic 所在的包,但如果需要,您也可以添加多个包:
public MyApplication() {
packages("stines.api.resources;stines.api.resources.impl");
register(new MyApplicationBinder());
}
编辑 2:删除了有关向后 Guice 绑定(bind)的注释
关于java - 使用 Jersey 2 的 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20564142/