How to use Swagger2 in spring boot
March 9, 2020 | Spring boot complete tutorial with example | No Comments
As we know every project required some documentation so that we get some help about the project. There is two option either you write yourself in a notepad or excel file about the project like details of endPoints in the project or use some tools that do documentation for you. I think second point is better we use some tool, so spring boot provide us a open source tool named Swagger2 for documentation. To use swagger2 in our application we have to follow below steps:
- Add required dependency in your pom.xml file.
- Create a Bean of Docker and provide your base package name .
- Create a controller class and define some end points for which you want documentation information.
- Run your application and hit the swagger2 URL.
Follow above Steps:
1- Add required dependency in your pom.xml file.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.1</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.1</version> </dependency>
2- Create a Bean of Docker and provide your base package name .
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; 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 public class SwaggerSpringBootApplication { public static void main(String[] args) { SpringApplication.run(SwaggerSpringBootApplication.class, args); } @Bean public Docket productApi() { return new Docket(DocumentationType.SPRING_WEB.SWAGGER_2).select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")).build(); } }
3- Create a controller class and define some end points for which you want documentation information.
package com.example.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @GetMapping("/") public String entryPoint() { return "This is entry point"; } @GetMapping("/api1") public String api1() { return "This is entry point"; } @GetMapping("/api2") public String api2() { return "This is api2"; } }
4- Run your application and hit the swagger2 URL i.e.
http://localhost:8080/swagger-ui.html
After hitting the URL you will get a UI that dispplay the information about your end points and you can also test your api.

Complete Code on GitHub: Swagger2 in Spring Boot