Spring 集成 Swagger 示例。

依赖

<!-- Swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- Swagger UI -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * 配置 Swagger2
     * http://localhost:8080/v2/api-docs
     * */
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any()) // 扫描所有接口
                .paths(PathSelectors.any()) // // 扫描所有URL
                .build()
                .apiInfo(apiInfo());
    }

    /**
     * 配置文档信息
     * */
    private ApiInfo apiInfo() {
    /* Params:
        title – title
        description – description
        version – version
        termsOfServiceUrl – termsOfServiceUrl
        contact – contact
        license – license
        licenseUrl – license url
        vendorExtensions – vendor extensions */
        return new ApiInfo(
                "SpringBoot 集成 Swagger2 示例",
                "示例参考:https://developer.ibm.com/zh/articles/j-using-swagger-in-a-spring-boot-project/",
                "API v1.0",
                "Term of service",
                new Contact("liaozibo", "liaozibo.com", "liaozibo@qq.com"),
                "MIT", "https://opensource.org/licenses/MIT", Collections.emptyList());
    }
}

注解

标注接口:

@RestController
@RequestMapping("/users")
@Api(tags = "用户相关接口")
public class UserController {

    private ConcurrentHashMap<Integer, User> users = new ConcurrentHashMap<>();

    @ApiOperation("新增用户接口")
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public void addUser(@RequestBody User user) {
        users.put(user.getId(), user);
    }
} 

标注实体:

@ApiModel("用户实体")
public class User {

    @ApiModelProperty("用户 id")
    private Integer id;
    
        public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
    
}

忽略

注解方式:

@ApiIgnore // 在文档隐蔽该接口
@DeleteMapping("{/id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteUser(@PathVariable int id) {
    users.remove(id);
}

配置方式:

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.liaozibo.swagger.demo.controller")) // 扫描指定包下的接口
            .paths(Predicates.or(PathSelectors.ant("/users"), PathSelectors.ant("/users/*"))) // 扫描指定 URL 下的接口
            .build();
}

自定义响应消息

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .useDefaultResponseMessages(false) // 不使用默认响应消息
            .globalResponseMessage(RequestMethod.GET, Arrays.asList( // 自定义全局响应消息
                    new ResponseMessageBuilder()
                            .code(500)
                            .message("服务器发生异常")
                            .responseModel(new ModelRef("Error"))
                            .build(),
                    new ResponseMessageBuilder()
                            .code(403)
                            .message("资源不可用")
                            .build()
            ));
}

访问文档

JSON 格式:http://localhost:8080/v2/api-docs

Swagger UI:http://localhost:8080/swagger-ui.html


参考:

项目地址:https://gitee.com/liaozibo1996/spring_boot_swagger2