REST API using Jersey 2

放肆的年华 提交于 2019-12-08 02:01:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!