Integrating Swagger 2 with Spring Boot for API Documentation and Testing

1. Project Dependencies

Add the following coordinates to your pom.xml to enable Swagger 2 and the enhanced Bootstrap UI theme:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.6</version>
</dependency>

2. Documentation Configuration

Create a dedicated configuration class to initialize the Docket bean and register static resource handlers for the UI assets.

@Configuration
@EnableSwagger2
public class ApiDocumentationSetup implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
    }

    @Bean
    public Docket buildApiDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.enterprise.asset.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(generateMetadata());
    }

    private ApiInfo generateMetadata() {
        return new ApiInfoBuilder()
                .title("Asset Tracking System")
                .description("Internal endpoints for hardware inventory management")
                .version("2.1.0")
                .contact(new Contact("Engineering Team", "https://internal.docs.corp", "devops@corp.io"))
                .build();
    }
}

3. Application Bootstrap

Enable Spring MVC configuration explicitly on the primary application class to insure proper resource resolution.

@SpringBootApplication
@EnableWebMvc
public class AssetPlatformApplication {
    public static void main(String[] args) {
        SpringApplication.run(AssetPlatformApplication.class, args);
    }
}

4. Annotation Reference

Annotation Target Purpose
@Api Class Attaches metadata to a REST controller
@ApiOperation Method Defines the summary and notes for an endpoint
@ApiParam Method Parameter Documents individual method arguments
@ApiImplicitParam Method Provides paramter documentation without direct binding
@ApiModel Class Describes a data transfer object used in requests/responses
@ApiModelProperty Field Details specific properteis within a model class

5. Implementation Example

Apply the annotations to your data models and controller methods to generate interactive documentation.

@Data
@ApiModel(description = "Payload for registering new hardware")
public class DeviceRegistrationDTO {

    @ApiModelProperty(value = "Unique device identifier", example = "1001")
    private Long deviceId;

    @ApiModelProperty(value = "Commercial model name", required = true)
    private String modelName;

    @ApiModelProperty(value = "Manufacturer serial code")
    private String serialNumber;

    @ApiModelProperty(value = "Acquisition date in ISO format")
    private String purchaseDate;

    @ApiModelProperty(value = "Current operational state")
    private String status;

    @ApiModelProperty(value = "Warranty duration in months")
    private Integer warrantyMonths;
}
@Api(tags = "Hardware Inventory Management")
@RestController
@RequestMapping("/api/devices")
public class DeviceController {

    private final DeviceService inventoryService;

    public DeviceController(DeviceService inventoryService) {
        this.inventoryService = inventoryService;
    }

    @ApiOperation(value = "Register a new device")
    @PostMapping
    public void registerDevice(@ApiParam("Registration payload") @RequestBody DeviceRegistrationDTO payload) {
        Device entity = DataMapper.convert(payload, Device.class);
        inventoryService.persist(entity);
    }

    @ApiOperation(value = "Remove device by identifier")
    @DeleteMapping("/{recordId}")
    public void removeDevice(@ApiParam("Target device ID") @PathVariable("recordId") Long recordId) {
        inventoryService.deleteByRecordId(recordId);
    }

    @ApiOperation(value = "Retrieve single device details")
    @GetMapping("/{recordId}")
    public DeviceSummaryVO fetchDevice(@ApiParam("Target device ID") @PathVariable("recordId") Long recordId) {
        Device entity = inventoryService.findByRecordId(recordId);
        return DataMapper.convert(entity, DeviceSummaryVO.class);
    }

    @ApiOperation(value = "Batch retrieval by identifiers")
    @GetMapping
    public List<DeviceSummaryVO> fetchMultipleDevices(@ApiParam("Comma-separated IDs") @RequestParam("ids") List<Long> ids) {
        List<Device> entities = inventoryService.findAllByRecordIds(ids);
        return DataMapper.convertList(entities, DeviceSummaryVO.class);
    }
}

6. UI Access Points

Once the application starts, navigate to either of the following addresses to view the generated documentation and execute test requests:

  • Enhanced UI: http://localhost:8080/doc.html
  • Default UI: http://localhost:8080/swagger-ui.html

Tags: Spring Boot swagger API Documentation java REST

Posted on Thu, 09 Jul 2026 17:07:41 +0000 by LacOniC