Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Spring Boot Integration with Swagger and Actuator

Tech May 15 1

API Documentation with Swagger

Swagger is an open-source framework built around the OpenAPI specification, designed to assist in designing, building, documenting, and consuming RESTful APIs. It comprises three main components: an editor for writing OpenAPI specs, a UI that renders interactive documentation, and a codegen tool for generating server stubs and client SDKs.

The primary advantages of Swagger include its intuitive UI for testing endpoints, automatic synchronization between code annotations and documentation, and the ability to import specs into tools like SoapUI for automated testing. However, it has limitations, such as the inability to persist request parameters in the web interface and difficulty handling complex authentication flows. These shortcomings are often mitigated by pairing Swagger with external tools like Postman.

Dependencies

To enable Swagger in a Spring Boot project, include the Springfox dependencies in your Maven configuration:

<dependencies>
    <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.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
</dependencies>

Configuration

Enable Swagger by adding the @EnableSwagger2 annotation to a configuration class. Create a Docket bean to customize the API documentation, specifying the base package to scan and metadata like title and version.

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket apiDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiMetadata())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.api"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiMetadata() {
        return new ApiInfoBuilder()
                .title("Product Management REST APIs")
                .description("APIs for managing product catalog")
                .version("2.0")
                .build();
    }
}

Data Model

Define a POJO to represent the data structure. Annotations like @ApiModel and @ApiModelProperty can be applied for richer descriptions.

public class Product {
    private Long itemId;
    private String productName;
    private Double price;
    // Getters and setters omitted
}

REST Controller

Swagger leverages annotations to document API endpoints. Use @ApiOperation to describe an operation and @ApiImplicitParam to describe parameters.

@RestController
@RequestMapping("/api/products")
public class ProductController {

    private static final Logger log = LoggerFactory.getLogger(ProductController.class);

    @ApiOperation(value = "Add a new product")
    @ApiImplicitParam(name = "product", value = "Product entity to add", required = true, dataType = "Product")
    @PostMapping
    public boolean create(@RequestBody Product product) {
        log.info("Creating product: {}", product);
        return true;
    }

    @ApiOperation(value = "Modify an existing product")
    @ApiImplicitParam(name = "product", value = "Updated product entity", required = true, dataType = "Product")
    @PutMapping
    public boolean modify(@RequestBody Product product) {
        log.info("Updating product: {}", product);
        return true;
    }

    @ApiOperation(value = "Remove a product")
    @ApiImplicitParam(name = "product", value = "Product entity to remove", required = true, dataType = "Product")
    @DeleteMapping
    public boolean remove(@RequestBody Product product) {
        log.info("Deleting product: {}", product);
        return true;
    }

    @ApiOperation(value = "Retrieve product details")
    @GetMapping
    public Product fetch() {
        log.info("Fetching product details");
        Product item = new Product();
        item.setItemId(100L);
        item.setProductName("Laptop");
        item.setPrice(999.99);
        return item;
    }
}

After launching the application, navigate to http://localhost:8080/swagger-ui.html to interact with the generated documentation.

Application Monitoring with Actuator

Spring Boot Actuator provides production-ready features to monitor and manage applications. By adding this dependency, numerous endpoints become available to expose operational data, such as application health, metrics, environment configurations, and thread dumps, accessible via HTTP or JMX.

It is important to note significant differences between Actuator 1.x and 2.x. The older version was tightly coupled with the Servlet API and Spring MVC, whereas version 2.x introduces a technology-agnostic, extensible model supporting both MVC and WebFlux.

Dependencies

Include the actuator starter in your project:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Configuration

Configure Actuator settings in application.yml. You can specify a separate management port, context path, disable security, and enable specific endpoints like shutdown.

server:
  port: 8081

management:
  security:
    enabled: false
  port: 9090
  context-path: /admin

endpoints:
  shutdown:
    enabled: true

info:
  app:
    name: product-catalog
    version: 2.0.0

Available Endpoints

Actuator provides several built-in endpoints to inspect the application state:

  • /autoconfig: Displays auto-configuration report.
  • /beans: Lists all configured Spring beans.
  • /dump: Shows thread dump information.
  • /env: Exposes environment variables and properties.
  • /health: Indicates application health status.
  • /mappings: Shows all @RequestMapping paths.
  • /metrics: Provides application metrics like memory usage and GC counts.
  • /info: Displays custom application information.
  • /shutdown: Gracefully shuts down the application (requires POST).

Verification

Upon startup, the console logs will indicate the main application port and the separate management port. Accessing endpoints like http://localhost:9090/admin/health or http://localhost:9090/admin/info will return JSON payloads containing the respective operational data.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.