How to Enable Swagger in Spring Boot Application | Swagger Spring Boot

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Here we will see how to enable swagger in spring boot application.
Spring Boot Starter 2.2.5
Swagger 2.7.0
Swagger UI 2.7.0
Gradle
Enabling swagger in spring boot gives us better accessibility of rest endpoints, we can group all rest points at a single dashboard and access them with default JSON templates.
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
</dependency>

plugins {
  id 'org.springframework.boot' version '2.2.5.RELEASE'
  id 'io.spring.dependency-management' version '1.0.9.RELEASE'
  id 'java'
}

group = 'com.onlinetutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
  mavenCentral()
}

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-web'
  testCompile('org.springframework.boot:spring-boot-starter-test')
  testCompile 'junit:junit:4.12'
  compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
  compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
}

Create a sample controller which will reverse the string, which we have passed.
package com.onlinetutorialspoint.controller;

import com.onlinetutorialspoint.domains.Response;
import com.onlinetutorialspoint.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Autowired
    HelloService helloService;

    @GetMapping("/api/{message}")
    @ResponseBody
    public ResponseEntity<Response> reverse(@PathVariable("message") String message) {
        Assert.notNull(message, "The message should not be null!");
        Response response= helloService.reverse(message);
        return new ResponseEntity<Response>(response, HttpStatus.OK);
    }
}

Create HelloService class, it will do actual reverse operation.
package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.domains.Response;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class HelloService {
    public Response reverse(String message){
       return Pattern.compile("\\s").splitAsStream(message).reduce((w1, w2) -> w2 + " " + w1).
                map(data->new Response(data)).get();
    }
}

Create domain class; which will act as a response JSON.
package com.onlinetutorialspoint.domains;

import org.springframework.stereotype.Component;

@Component
public class Response {
    private String reversed;

    public Response() {
    }

    public Response(String reversed) {
        this.reversed = reversed;
    }

    public String getReversed() {
        return reversed;
    }
}

Create Spring Boot started class
package com.onlinetutorialspoint;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
@Configuration
public class SpringBootService {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootService.class, args);
  }
  @Bean
  public Docket productApi() {
    return new Docket(DocumentationType.SWAGGER_2).select()
        .apis(RequestHandlerSelectors.basePackage("com.onlinetutorialspoint")).build();
  }
}

@EnableSwagger2 enables the swagger API.
Create Docket object for swagger documentation type to enable documentation for the specified base package and build the API.
Build and Run:
gradlew build

> Task :test
09:19:49.283 [SpringContextShutdownHook] DEBUG org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@1c5f2
61f, started on Wed Mar 25 09:19:46 IST 2020

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.2.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 20s
5 actionable tasks: 4 executed, 1 up-to-date

Run:
gradlew bootRun

> Task :bootRun

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.5.RELEASE)

2020-03-25 09:23:54.281  INFO 18108 --- [           main] c.o.SpringBootService                    : Starting SpringBootService on DESKTOP-RN4SMHT with PID 18108 (D:\work\sample-spring-a
pplication\build\classes\java\main started by Lenovo in D:\work\sample-spring-application)
2020-03-25 09:23:54.286  INFO 18108 --- [           main] c.o.SpringBootService                    : No active profile set, falling back to default profiles: default
2020-03-25 09:23:56.344  INFO 18108 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-03-25 09:23:56.359  INFO 18108 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-03-25 09:23:56.360  INFO 18108 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-03-25 09:23:56.568  INFO 18108 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-03-25 09:23:56.568  INFO 18108 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2196 ms
2020-03-25 09:23:57.274  INFO 18108 --- [           main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [springfox.documentation.swagger2.web.Swag
ger2Controller#getDocumentation(String, HttpServletRequest)]
2020-03-25 09:23:57.554  INFO 18108 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-03-25 09:23:57.826  INFO 18108 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2020-03-25 09:23:57.850  INFO 18108 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2020-03-25 09:23:57.919  INFO 18108 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
2020-03-25 09:23:58.119  INFO 18108 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-03-25 09:23:58.123  INFO 18108 --- [           main] c.o.SpringBootService                    : Started SpringBootService in 4.505 seconds (JVM running for 5.189)
<=========----> 75% EXECUTING [2m 11s]

Access the application with swagger UI endpoint :
http://localhost:8080/swagger-ui.htm
Click on the hello-controller endpoint and you can see the below API details.
Spring Boot Rest Web Services Example
Swagger Documentation
Happy Learning 🙂

Spring Boot How to change the Tomcat to Jetty Server
How to Configure Spring Profile in Tomcat ?
How to use Spring Boot Random Port
How to set Spring Boot SetTimeZone
Spring Boot Environment Properties reading based on activeprofile
Spring Boot Basic Authentication Example
Step By Step Spring Boot Docker Deployment Example
Spring Boot PDF iText integration with String Template
SSL Spring Boot HTTPs Enabling Example
How to Enable Spring Boot CORS Example – @CrossOrigin
Spring JdbcTemplate CRUD Application
Spring Boot MongoDB + Spring Data Example
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Validation Login Form Example

Spring Boot How to change the Tomcat to Jetty Server
How to Configure Spring Profile in Tomcat ?
How to use Spring Boot Random Port
How to set Spring Boot SetTimeZone
Spring Boot Environment Properties reading based on activeprofile
Spring Boot Basic Authentication Example
Step By Step Spring Boot Docker Deployment Example
Spring Boot PDF iText integration with String Template
SSL Spring Boot HTTPs Enabling Example
How to Enable Spring Boot CORS Example – @CrossOrigin
Spring JdbcTemplate CRUD Application
Spring Boot MongoDB + Spring Data Example
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Validation Login Form Example
 


Δ
 Spring Boot – Hello World
 Spring Boot – MVC Example
 Spring Boot- Change Context Path
 Spring Boot – Change Tomcat Port Number
 Spring Boot – Change Tomcat to Jetty Server
 Spring Boot – Tomcat session timeout
 Spring Boot – Enable Random Port
 Spring Boot – Properties File
 Spring Boot – Beans Lazy Loading
 Spring Boot – Set Favicon image
 Spring Boot – Set Custom Banner
 Spring Boot – Set Application TimeZone
 Spring Boot – Send Mail
 Spring Boot – FileUpload Ajax
 Spring Boot – Actuator
 Spring Boot – Actuator Database Health Check
 Spring Boot – Swagger
 Spring Boot – Enable CORS
 Spring Boot – External Apache ActiveMQ Setup
 Spring Boot – Inmemory Apache ActiveMq
 Spring Boot – Scheduler Job
 Spring Boot – Exception Handling
 Spring Boot – Hibernate CRUD
 Spring Boot – JPA Integration CRUD
 Spring Boot – JPA DataRest CRUD
 Spring Boot – JdbcTemplate CRUD
 Spring Boot – Multiple Data Sources Config
 Spring Boot – JNDI Configuration
 Spring Boot – H2 Database CRUD
 Spring Boot – MongoDB CRUD
 Spring Boot – Redis Data CRUD
 Spring Boot – MVC Login Form Validation
 Spring Boot – Custom Error Pages
 Spring Boot – iText PDF
 Spring Boot – Enable SSL (HTTPs)
 Spring Boot – Basic Authentication
 Spring Boot – In Memory Basic Authentication
 Spring Boot – Security MySQL Database Integration
 Spring Boot – Redis Cache – Redis Server
 Spring Boot – Hazelcast Cache
 Spring Boot – EhCache
 Spring Boot – Kafka Producer
 Spring Boot – Kafka Consumer
 Spring Boot – Kafka JSON Message to Kafka Topic
 Spring Boot – RabbitMQ Publisher
 Spring Boot – RabbitMQ Consumer
 Spring Boot – SOAP Consumer
 Spring Boot – Soap WebServices
 Spring Boot – Batch Csv to Database
 Spring Boot – Eureka Server
 Spring Boot – MockMvc JUnit
 Spring Boot – Docker Deployment