spring-boot Creating a Rest Service with JERSEY and Spring Boot


Example

Jersey is one of the many frameworks available to create Rest Services, This example will show you how to create Rest Services using Jersey and Spring Boot

1.Project Setup

You can create a new project using STS or by using the Spring Initializr page. While creating a project, include the following dependencies:

  1. Jersey (JAX-RS)
  2. Web

2.Creating a Controller

Let us create a controller for our Jersey Web Service

@Path("/Welcome")
@Component
public class MyController {
    @GET
    public String welcomeUser(@QueryParam("user") String user){
        return "Welcome "+user;
    }    
}

@Path("/Welcome") annotation indicates to the framework that this controller should respond to the URI path /Welcome

@QueryParam("user") annotation indicates to the framework that we are expecting one query parameter with the name user

3.Wiring Jersey Configurations

Let us now configure Jersey Framework with Spring Boot: Create a class, rather a spring component which extends org.glassfish.jersey.server.ResourceConfig:

@Component
@ApplicationPath("/MyRestService")
public class JerseyConfig extends ResourceConfig {
    /**
     * Register all the Controller classes in this method 
     * to be available for jersey framework
     */
    public JerseyConfig() {
        register(MyController.class);
    }

}

@ApplicationPath("/MyRestService") indicates to the framework that only requests directed to the path /MyRestService are meant to be handled by the jersey framework, other requests should still continue to be handeld by spring framework.

It is a good idea to annotate the configuration class with @ApplicationPath, otherwise all the requests will be handled by Jersey and we will not be able to bypass it and let a spring controller handle it if required.

4.Done

Start the application and fire a sample URL like (Assuming you have configured spring boot to run on port 8080):

http://localhost:8080/MyRestService/Welcome?user=User

You should see a message in your browser like:

Welcome User

And you are done with your Jersey Web Service with Spring Boot