JavaScript Required

We're sorry, but we doesn't work properly without JavaScript enabled.

Getting started with Jersey and Spring Boot

On account of being at the cusp of API economy, Spring Boot and Jersey have been a boon to all developers. With a 30% adoption rate, Spring Boot is a popular framework, and the Jersey support makes it even more irresistible to use. In 2015, when Jersey support was introduced, developers rejoiced as they could now build RESTful APIs and deploy it on Tomcat or any other Spring Boot containers.

This article will explore how to get started with using Jersey with Spring Boot to develop an application.

We will learn how to configure and create JAX-RS 2.0 REST APIs. For the purpose, we will be making use of Spring Boot and Jersey frameworks. This example application here uses Jersey’s ServletContainer to deploy the REST APIs.

Create Spring Boot Application with Spring Initialyzr

At the outset, you need to start with the Spring Initializr portal, which is the common point for all Spring Boot related development. Now, initiate or create a Spring Boot application that has a dependency on Jersey (JAX-RS).

Make sure this project gets generated as a .zip (or a compressed version) file. At this point, it becomes amply clear that we would be importing this code into Eclipse for further development. Hence, the next step would be to extract these files at a location on your computer from where you can comfortably import, modify and save code files through Eclipse. Once you open Eclipse, import this project as an ‘Existing maven application‘.

To verify if the dependency was added, look out for the spring-boot-starter-jersey dependency in the maven file.

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jersey</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>

Create JAX-RS REST Resources

Now, we create a few JAX-RS resources that will be accessed and run during our testing phase. For this purpose, take a look at the example ResourceCode.java file which on executing will provide a ResourceCode class.

ResourceCode.java:

import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "exusers") @Path("/exusers") public class ResourceCode { private static Map < Integer, User > DB = new HashMap < > (); @GET @Produces("application/json") public Users getAllUsers() { Users exusers = new Users(); exusers.setUsers(new ArrayList < > (DB.values())); return exusers; } @POST @Consumes("application/json") public Response createUser(User cust) throws URISyntaxException { if (cust.getFirstName() == null || cust.getLastName() == null) { return Response.status(400).entity("Please provide all mandatory inputs").build(); } cust.setId(DB.values().size() + 1); cust.setU("/cust-management/" + cust.getId()); DB.put(cust.getId(), cust); return Response.status(201).contentLocation(new URI(cust.getUri())).build(); } @GET @Path("/{id}") @Produces("application/json") public Response getUserById(@PathParam("id") int id) throws URISyntaxException { User cust = DB.get(id); if (cust == null) { return Response.status(404).build(); } return Response .status(200) .entity(cust) .contentLocation(new URI("/cust-management/" + id)).build(); } @PUT @Path("/{id}") @Consumes("application/json") @Produces("application/json") public Response updateUser(@PathParam("id") int id, User cust) throws URISyntaxException { User temp = DB.get(id); if (cust == null) { return Response.status(404).build(); } temp.setGivenName(cust.getFirstName()); temp.setSurName(cust.getLastName()); DB.put(temp.getId(), temp); return Response.status(200).entity(temp).build(); } @DELETE @Path("/{id}") public Response deleteUser(@PathParam("id") int id) throws URISyntaxException { User cust = DB.get(id); if (cust != null) { DB.remove(cust.getId()); return Response.status(200).build(); } return Response.status(404).build(); } static { User user1 = new User(); user1.setId(1); user1.setGivenName("Aayusi"); user1.setSurName("Biswas"); user1.setU("/cust-management/1"); User user2 = new User(); user2.setId(2); user2.setGivenName("Abra"); user2.setSurName("Kadabra"); user2.setU("/cust-management/2"); DB.put(user1.getId(), user1); DB.put(user2.getId(), user2); } }

Users.java

import java.util.ArrayList; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "exusers") public class Users { @XmlElement(name="cust") private ArrayList<User> exusers; public ArrayList<User> getUsers() { return exusers; } public void setUsers(ArrayList<User> exusers) { this.exusers = exusers; } }

User.java

package com.howtodoinjava.jerseydemo; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "cust") public class User implements Serializable { private static final long serialVersionUID = 1L; @XmlAttribute(name = "id") private int id; @XmlAttribute(name="u") private String u; @XmlElement(name = "givenName") private String givenName; @XmlElement(name = "surName") private String surName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getGivenName() { return givenName; } public void setGivenName(String givenName) { this.givenName = givenName; } public String getSurName() { return surName; } public void setSurName(String surName) { this.surName = surName; } public String getU() { return u; } public void setU(String u) { this.u = u; } }

Jersey Configuration

Having these files into the repository will mean that you have JAX-RS resource files and it will be accessed by a spring boot application. Make sure first-hand that these contain Jersey dependency. On that note, you can then proceed to register this resource as a Jersey resource.

import org.glassfish.jersey.server.ResourceConfig; import org.springframework.stereotype.Component; @Component public class JerseyConfig extends ResourceConfig { public JerseyConfig() { register(ResourceCode.class); } }

Spring Boot boasts of the auto-scan feature via which it primarily scans the @Componenet annotation. The presence of the same enables the class to be successfully registered.

ResourceConfig, on the other hand, is a helper class that provides high complexity support and advanced capabilities to aid and ease down the registration process of JAX-RS components.

Finally, extend the spring boot application with SpringBootServletInitializer.

import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class JerseydemoApplication extends SpringBootServletInitializer { public static void main(String[] args) { new JerseydemoApplication().configure(new SpringApplicationBuilder(JerseydemoApplication.class)).run(args); } }

Finale

Finally, you can reap the fruits of the process. Execute this project as a Spring boot application. Now you can have a hand at testing these resources.

This article from Aegis Softtech Java Development Company, about how to get started with jerseys for Spring boot applications. Now you can easily develop Restful Jersey web services along with Spring Boot. It aims at an informative, practical and easy take on creating a Restful web service.