SSM 配置 Swagger2 接口文档引擎

POM


增加 Swagger2 所需依赖,pom.xml 配置如下:

<!-- Swagger2 Begin -->
<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>
<!-- Swagger2 End -->

配置 Swagger2


注意:RequestHandlerSelectors.basePackage("com.yuu.ymall.controller")为 Controller 包路径,不然生成的文档扫描不到接口

创建一个名为 Swagger2Config 的 Java 配置类,代码如下:

package com.yuu.ymall.common.swagger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/** * @Classname Swagger2Confinguration * @Date 2019/5/12 11:33 * @Created by Yuu */
@Configuration  // 让 Spring 来加载该配置类
@EnableWebMvc   // 非 Spring Boot 需启用
@EnableSwagger2 // 启用 Swagger2
@ComponentScan(basePackages = "com.yuu.ymall.controller")
public class Swagger2Configuration {

    public static final Logger log = LoggerFactory.getLogger(Swagger2Configuration.class);

    @Bean
    public Docket createRestApi() {
        log.info("开始加载Swagger2...");
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 扫描指定包中的 swagger 注解
                //.apis(RequestHandlerSelectors.basePackage("com.yuu.ymall.controller"))
                // 扫描所有有注解的 api,用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("YMall API Documentation")
                .description("XMall 商城管理后台API接口")
                .termsOfServiceUrl("https://www.71yuu.com")
                .contact(new Contact("Yuu", "https://www.71yuu.com", "[email protected]"))
                .version("1.0.0")
                .build();
    }
}

配置 spring-mvc.xml


<!-- Swagger 配置 -->
<mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
<mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>

使用 Swagger2


在 Controller 中增加 Swagger2 相关注解,代码如下:

/** * 分页查询 * * @param pageNum * @param pageSize * @param tbSysUserJson * @return */
@ApiOperation(value = "管理员分页查询")
@ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "int", paramType = "path"),
        @ApiImplicitParam(name = "pageSize", value = "笔数", required = true, dataType = "int", paramType = "path"),
        @ApiImplicitParam(name = "tbSysUserJson", value = "管理员对象 JSON 字符串", required = false, dataTypeClass = String.class, paramType = "json")
})
@RequestMapping(value = "page/{pageNum}/{pageSize}", method = RequestMethod.GET)
public BaseResult page(
        @PathVariable(required = true) int pageNum,
        @PathVariable(required = true) int pageSize,
        @RequestParam(required = false) String tbSysUserJson
) throws Exception {

    TbSysUser tbSysUser = null;
    if (tbSysUserJson != null) {
        tbSysUser = MapperUtils.json2pojo(tbSysUserJson, TbSysUser.class);
    }
    PageInfo pageInfo = adminService.page(pageNum, pageSize, tbSysUser);

    // 分页后的结果集
    List<TbSysUser> list = pageInfo.getList();

    // 封装 Cursor 对象
    BaseResult.Cursor cursor = new BaseResult.Cursor();
    cursor.setTotal(new Long(pageInfo.getTotal()).intValue());
    cursor.setOffset(pageInfo.getPageNum());
    cursor.setLimit(pageInfo.getPageSize());

    return BaseResult.ok(list, cursor);
}

Swagger 注解说明


Swagger 通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。

  • @Api:修饰整个类,描述 Controller 的作用
  • @ApiOperation:描述一个类的一个方法,或者说一个接口
  • @ApiParam:单个参数描述
  • @ApiModel:用对象来接收参数
  • @ApiProperty:用对象接收参数时,描述对象的一个字段
  • @ApiResponse:HTTP 响应其中 1 个描述
  • @ApiResponses:HTTP 响应整体描述
  • @ApiIgnore:使用该注解忽略这个API
  • @ApiError:发生错误返回的信息
  • @ApiImplicitParam:一个请求参数
  • @ApiImplicitParams:多个请求参数

访问 Swagger2


访问地址:http://ip:port/swagger-ui.html