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);
}
}
This works: