How to Integrate Swagger‑UI for Complete API Documentation in a Spring Boot Mall Project
This tutorial walks through integrating Swagger‑UI into the mall‑tiny Spring Boot project, covering Maven dependencies, Java configuration, adding Swagger annotations to controllers, customizing MyBatis Generator to emit @ApiModelProperty, regenerating model code, and finally viewing and testing the generated API docs via the Swagger‑UI interface.
This article explains how the mall project integrates Swagger‑UI to provide a comprehensive online API documentation.
Project Framework Introduction
Swagger‑UI
Swagger‑UI is a collection of HTML, JavaScript, and CSS that can dynamically generate online API documentation based on annotations.
Common Annotations
@Api – used on Controller classes to generate controller‑level documentation.
@ApiOperation – used on controller methods to generate method‑level documentation.
@ApiParam – used on method parameters to generate parameter documentation.
@ApiModelProperty – used on entity fields to generate field documentation when the class is used as a request or response model.
Integrate Swagger‑UI
Add Project Dependencies
<!-- Swagger‑UI API documentation tool -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>Add Swagger‑UI Configuration
package com.macro.mall.tiny.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SwaggerUI Demo")
.description("mall‑tiny")
.contact("macro")
.version("1.0")
.build();
}
}Add Swagger Annotations to PmsBrandController
package com.macro.mall.tiny.controller;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.mbg.model.PmsBrand;
import com.macro.mall.tiny.service.PmsBrandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Api(tags = "PmsBrandController", description = "商品品牌管理")
@Controller
@RequestMapping("/brand")
public class PmsBrandController {
@Autowired
private PmsBrandService brandService;
private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);
@ApiOperation("获取所有品牌列表")
@RequestMapping(value = "listAll", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<PmsBrand>> getBrandList() {
return CommonResult.success(brandService.listAllBrand());
}
@ApiOperation("添加品牌")
@RequestMapping(value = "create", method = RequestMethod.POST)
@ResponseBody
public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {
int count = brandService.createBrand(pmsBrand);
if (count == 1) {
LOGGER.debug("createBrand success:{}", pmsBrand);
return CommonResult.success(pmsBrand);
} else {
LOGGER.debug("createBrand failed:{}", pmsBrand);
return CommonResult.failed("操作失败");
}
}
// Additional CRUD methods with @ApiOperation and @RequestMapping omitted for brevity
}Modify MyBatis Generator Comment Generation Rules
package com.macro.mall.tiny.mbg;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;
import java.util.Properties;
/**
* Custom comment generator that adds Swagger @ApiModelProperty annotations.
*/
public class CommentGenerator extends DefaultCommentGenerator {
private boolean addRemarkComments = false;
private static final String EXAMPLE_SUFFIX = "Example";
private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME = "io.swagger.annotations.ApiModelProperty";
@Override
public void addConfigurationProperties(Properties properties) {
super.addConfigurationProperties(properties);
this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
}
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
String remarks = introspectedColumn.getRemarks();
if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
if (remarks.contains("\"")) {
remarks = remarks.replace("\"", "'");
}
field.addJavaDocLine("@ApiModelProperty(value = \"" + remarks + "\")");
}
}
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
super.addJavaFileComment(compilationUnit);
if (!compilationUnit.isJavaInterface() && !compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)) {
compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
}
}
}Run Code Generator to Regenerate MBG Package
Execute the main method of com.macro.mall.tiny.mbg.Generator. The regenerated PmsBrand model now contains @ApiModelProperty annotations derived from database column comments.
Run Project and View Result
Start the Spring Boot application and open the Swagger‑UI interface:
URL: http://localhost:8080/swagger-ui.html
Request parameter documentation screenshot:
Response documentation screenshot:
Directly Test Interfaces in Online Documentation
Project Source Code
https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-02
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
