Configuring Swagger in Spring Boot Application


SpringBoot Initializr:

Initialize a Sample Spring Boot Application using Spring Initializr :

Key in the Group, artifact id and the name for your sample project .

Choose your favourite language, it can be Java/Kotlin/Groovy.

Also choose the language version, Packaging option and the Project to be built in. It can be Maven or Gradle.

For this demo, I have Chosen Java 8 for language , Maven as a build tool and packaging as jar

Once you have clicked generate, it will generate a zip file with required dependencies been added to the pom.xml file. Import it as a Maven project in your IDE. I have chosen Eclipse for this demo.

Maven Dependency

Add the SpringFox Swagger Dependency as below to the pom.xml

Note: For Spring boot 3 version, adding “springfox-boot-starter” dependency is enough and we don’t need to add swagger ui dependency and also not to include @EnableSwagger2 in the starter class.

Then run command :mvn clean install to download the swagger dependency to your project.

Code Changes

To enable Swagger in the Spring Boot Application, need to make code changes in below sections

Spring Boot Starter Class

Need to define a Bean “Docket” to customize the Swagger Documentation. Say if we access the swagger UI : http://localhost:<<PORT_NO>>/swagger-ui/index.html. It will provide api docs for the controller been defined along with the error controllers. To restrict API definition to the controllers been defined in our application, need to have this docket Bean with the PathSelectors and RequestHandlerSelectors point to the controllers defined for our application as below. Here I restrict the scan to the package “com.nikki.demo.controller” to scan for this controller package

Spring Rest Controller

Then to have the controller APIs to display more additional information about the endpoint been exposed, can add API operation annotation to it.

Here each endpoint been annotated with @ApiOperation to give more details about the endpoint

Accessing the Swagger UI

Then, hit the Swagger UI as below ( after running your application as mvn clean spring-boot:run )

Happy Learning !

Bharathy Poovalingam

Related Blogs