使用Jersey 2的REST API

时间:2013-12-13 10:27:22

标签: java rest jersey hk2

我想使用Jersey 2实现REST API,我希望将资源分为接口及其实现,例如:

@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);
    }
}

2 个答案:

答案 0 :(得分:2)

编辑1:您需要告诉泽西岛您的资源在哪里:

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绑定的说明

答案 1 :(得分:1)

这有效:

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        registerClasses(HelloLogicResource.class);
    }
}