Here we will see how to enable swagger in spring boot application.
Technologies:
- Spring Boot Starter 2.2.5
- Swagger 2.7.0
- Swagger UI 2.7.0
- Gradle
Enable Swagger in Spring Boot:
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.
Application Structure:
Dependencies:
gradle
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
maven
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
build.gradle
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.
HelloController.java
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.
HelloService.java
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.
Response.java
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
SpringBootService.java
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
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
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.
References:
Happy Learning 🙂