Configure Swagger With Jersey and Spring Boot

We are going to configure Swagger With Jersey and Spring Boot. We saw applications are moving towards micro-services architecture. one of the important aspects of API development is API documentation. Great documentation results in proper experience in API consumption. We are going to use and Configure Swagger and Swagger UI for API documentation along with Jersey and Spring Boot.

Swagger is Used for standardizing API documentation and provide a consistent specification. Swagger UI  helps in visualizing and interact with our API’s.

Integration of Spring with Swagger is a straightforward task with  Spring provided annotations. Using Spring Boot Swagger with JAX-RS is a bit tricky task. Let’s continue and create a  Spring Boot Jersey Project referring our post Spring Boot Jersey Example.

Project Dependencies:-

  1. Spring Boot
  2. swagger-jersey2-jaxrs
  3. spring-boot-starter-web

Here is our pom.xml with spring boot swagger maven dependency and other required dependencies.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.frugalis</groupId>
	<artifactId>myRest</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>SpringBoot-Jersey</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

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

		<dependency>
			<artifactId>tomcat-embed-websocket</artifactId>
			<groupId>org.apache.tomcat.embed</groupId>
			<scope>provided</scope>
		</dependency>
		
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-links</artifactId>
			<version>3.1.1.Final</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

	<dependency>
		<groupId>io.swagger</groupId>
		<artifactId>swagger-jersey2-jaxrs</artifactId>
		<version>1.5.20</version>
	</dependency>


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

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

Configuration Of Swagger and Jersey:-

Now we have already added swagger maven dependencies, now it’s the time to configure swagger with jersey and spring boot. Lets  add a swagger configuration in our Jersey Config as below.

package com.frugalis.SpringBootJersey;

import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;

import javax.annotation.PostConstruct;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;


@Component
@ApplicationPath("/api")
public class JerseyConfig extends ResourceConfig {

	@Autowired
	public JerseyConfig(ObjectMapper objectMapper) {
	
		packages("com.frugalis.resourcesImpl");		
		register(new ObjectMapperContextResolver(objectMapper));
	}

	@Provider
	public static class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
		private final ObjectMapper mapper;
		public ObjectMapperContextResolver(ObjectMapper mapper) {
			this.mapper = mapper;
		}

		@Override
		public ObjectMapper getContext(Class<?> type) {
			return mapper;
		}
	
	}
	
	 @PostConstruct
	  public void init() {
	    // Register components where DI is needed
	    this.SwaggerConfig();
	  }
	private void SwaggerConfig() {
		this.register(ApiListingResource.class);
		this.register(SwaggerSerializers.class);
		
	    BeanConfig swaggerConfigBean = new BeanConfig();
	    swaggerConfigBean.setConfigId("Frugalis Swagger Jersey Example");
	    swaggerConfigBean.setTitle("Using Swagger ,Jersey And Spring Boot ");
	    swaggerConfigBean.setVersion("v1");
	    swaggerConfigBean.setContact("frugalisAdmin");
	    swaggerConfigBean.setSchemes(new String[] { "http", "https" });
	    swaggerConfigBean.setBasePath("/api");
	    swaggerConfigBean.setResourcePackage("com.frugalis.resources");
	    swaggerConfigBean.setPrettyPrint(true);
	    swaggerConfigBean.setScan(true);
	  }
}

We are setting basepath asswaggerConfigBean.setBasePath("/api") this path could be anything. On successful setup, we can check our swagger setup is working or not by going to http://localhost:8080/api/swagger.json

Once we get an output JSON as response, our first step to Configure Swagger With Jersey and Spring Boot is Done.

Now the next step is Configuring Swagger UI.

Configure and Setup Swagger UI:-

Visit Swagger UI GitHub project and download dist version of the Project. Extract contents and move the dist content to /src/main/resources/static , we can create the folder structure if it is not present. The dist folder under the GitHub project contains  JavaScript, CSS, images and HTML files used for swagger UI.

We need to update index.htmlinside forsrc/main/resources/static/index.html Swagger UI to find the configuration and load the UI accordingly. Replace text withhttp://petstore.swagger.io/v2/swagger.json to your  swagger.json URL. In this case, our swagger.json is located at http://localhost:8080/api/swagger.json

<script>
    window.onload = function() {

      // Build a system
      const ui = SwaggerUIBundle({
        url: "api/swagger.json",
        dom_id: '#swagger-ui',
        deepLinking: true,
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIStandalonePreset
        ],
        plugins: [
          SwaggerUIBundle.plugins.DownloadUrl
        ],
        layout: "StandaloneLayout"
      })

      window.ui = ui
    }
  </script>

Testing:-

configure swagger with jersey and spring boot
[sociallocker id=”1183″]

 Download

[/sociallocker]