How to Configure Swagger/OpenAPI Documentation in the Mall Project

Configure Swagger/OpenAPI documentation by extending BaseSwaggerConfig and returning a customized SwaggerProperties instance from the swaggerProperties() method in each module.

The Mall project implements a centralized Swagger configuration architecture that standardizes API documentation across its microservices. To configure Swagger/OpenAPI documentation effectively, you extend the base configuration class and customize the properties for each specific module such as admin, portal, or search.

Architecture Overview

The configuration relies on three core components that separate common functionality from module-specific settings.

BaseSwaggerConfig

Located in mall-common/src/main/java/com/macro/mall/common/config/BaseSwaggerConfig.java, this abstract class provides the common Docket bean creation, security scheme configuration, and a critical BeanPostProcessor that fixes Springfox compatibility issues with Spring Boot 2.6+.

SwaggerProperties

The SwaggerProperties POJO in mall-common/src/main/java/com/macro/mall/common/domain/SwaggerProperties.java holds all configurable values including the base package, API metadata (title, description, version), contact information, and security flags.

Module-Specific Configuration

Each module contains its own SwaggerConfig class (e.g., mall-admin/src/main/java/com/macro/mall/config/SwaggerConfig.java) that extends BaseSwaggerConfig and provides concrete property values via the builder pattern.

Configuration Flow

When the Spring application context initializes, the following sequence occurs:

  1. Spring instantiates the module's SwaggerConfig bean annotated with @Configuration and @EnableSwagger2.
  2. The configuration overrides swaggerProperties() to return a SwaggerProperties object built using the fluent builder API.
  3. BaseSwaggerConfig#createRestApi() consumes these properties to construct a Docket bean:
    • API scanning: RequestHandlerSelectors.basePackage(swaggerProperties.getApiBasePackage()) limits documentation generation to specific controller packages.
    • Metadata: Title, description, version, and contact details populate the ApiInfo object.
    • Security: When enableSecurity is true, an Authorization header ApiKey is added along with a SecurityContext matching /*/.* routes.
  4. The BeanPostProcessor returned by generateBeanPostProcessor() removes Springfox's PatternParser-based handler mappings to ensure compatibility with newer Spring Boot versions.

Customizing Swagger per Module

To adjust documentation for a specific service, create or modify the module's SwaggerConfig class:

@Configuration
@EnableSwagger2
public class SwaggerConfig extends BaseSwaggerConfig {

    @Override
    public SwaggerProperties swaggerProperties() {
        return SwaggerProperties.builder()
                .apiBasePackage("com.macro.mall.admin.controller")
                .title("mall-admin 系统")
                .description("mall 后台管理系统接口文档")
                .contactName("macro")
                .contactUrl("https://github.com/macrozheng/mall")
                .contactEmail("macro@example.com")
                .version("1.0")
                .enableSecurity(true)
                .build();
    }

    @Bean
    public BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return generateBeanPostProcessor();
    }
}

Key Configuration Properties

  • apiBasePackage: Specifies the package to scan for @RestController and @RequestMapping annotations (e.g., "com.macro.mall.portal.controller").
  • title / description: Controls the header text and descriptive content displayed in the Swagger UI.
  • contactName, contactUrl, contactEmail: Populates the contact section of the documentation.
  • enableSecurity: When set to true, adds an Authorize button to the UI and includes the Authorization header in the OpenAPI spec.
  • version: Displays the API version string at the top of the documentation interface.

Dependencies and Compatibility

The project uses Springfox 3.0.0 declared in the parent pom.xml:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>${springfox-swagger.version}</version>
</dependency>

Additional dependencies on swagger-models and swagger-annotations (v1.6.0) prevent NumberFormatException errors when running on Spring Boot 2.7+.

Accessing the Documentation

After starting the Spring Boot application, access the Swagger UI at:

http://localhost:{port}/swagger-ui/index.html

Replace {port} with your configured HTTP port (default 8080). The interface displays only controllers within the configured apiBasePackage.

For the raw OpenAPI specification, use:

http://localhost:{port}/v2/api-docs

Adding Swagger to a New Module

To implement Swagger documentation in a new module (e.g., mall-payment):

  1. Ensure the module inherits the Springfox starter dependency from the parent POM.
  2. Create a SwaggerConfig class extending BaseSwaggerConfig in the module's config package.
  3. Override swaggerProperties() and set apiBasePackage to the module's controller package (e.g., "com.macro.mall.payment.controller").
  4. Include the BeanPostProcessor bean to maintain Spring Boot compatibility.
  5. Verify the @SpringBootApplication scan path includes the configuration class.

Configuring JWT Authorization

When enableSecurity is true, the generated OpenAPI specification includes:

"securitySchemes": [
  {
    "type": "apiKey",
    "name": "Authorization",
    "in": "header"
  }
],
"security": [
  {
    "Authorization": []
  }
]

To authenticate requests in the Swagger UI:

  1. Navigate to http://localhost:8080/swagger-ui/index.html.
  2. Click the Authorize button in the top-right corner.
  3. Enter the JWT token in the format: Bearer eyJhbGci....
  4. Click Authorize to apply the token to subsequent requests.

The actual JWT validation logic resides in mall-security/src/main/java/com/macro/mall/security/component/JwtAuthenticationTokenFilter.java.

Summary

  • Extend BaseSwaggerConfig in each module to inherit common Swagger setup and Spring Boot compatibility fixes.
  • Override swaggerProperties() to return a SwaggerProperties builder instance with module-specific metadata, package scanning paths, and security settings.
  • Include the BeanPostProcessor bean to prevent Springfox compatibility issues with Spring Boot 2.6 and later.
  • Set enableSecurity to true for protected modules requiring JWT tokens, or false for public APIs.
  • Access the UI at /swagger-ui/index.html and the raw spec at /v2/api-docs.

Frequently Asked Questions

How do I enable or disable JWT authentication in Swagger UI?

Set the enableSecurity property in your SwaggerProperties builder to true (to show the Authorize button and require JWT tokens) or false (for public APIs that don't require authentication). When enabled, users must click Authorize in the Swagger UI and provide a Bearer token before testing endpoints.

What is the purpose of the BeanPostProcessor in Swagger configuration?

The BeanPostProcessor returned by generateBeanPostProcessor() in BaseSwaggerConfig fixes a critical compatibility issue between Springfox and Spring Boot 2.6+ by removing handler mappings that rely on PatternParser. Without this processor, the Swagger UI fails to load on newer Spring Boot versions due to path pattern parsing changes.

How do I change which controllers appear in the Swagger documentation?

Modify the apiBasePackage property in your module's SwaggerConfig to point to the specific package containing your controllers (e.g., com.macro.mall.search.controller). Only classes annotated with @RestController or @RequestMapping within this package and its subpackages will appear in the generated documentation.

Where is the Swagger/OpenAPI JSON specification located?

The raw OpenAPI (Swagger 2.0) JSON is available at http://localhost:{port}/v2/api-docs when the application is running. This endpoint returns the complete API specification including all endpoints, parameters, and security schemes defined in your SwaggerProperties configuration.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →