说明
前几天我们使用了Swagger来通过代码暴露我们的API接口,这次来使用程序猿DD翟永超大佬写的spring-boot-starter-swagger版本来通过starter版本更快速的使用Swagger,项目博客:http://blog.didispace.com/spring-boot-starter-swagger-1.1.0/,github地址:https://github.com/SpringForAll/spring-boot-starter-swagger,本项目的github地址:https://github.com/Yunlingfly/springboot-starter-swagger
快速开始
更新pom.xml引入swagger-spring-boot-starter:
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
更新application.yml:
server:
port: 8081
swagger:
# 是否启用swagger,默认:true
enabled: true
# 标题
title: "Spring Boot 测试使用 Swagger2 构建RESTful API"
contact:
# 维护人
name: "yunlingfly"
email: "508821881@qq.com"
url: "https://www.yunlingfly.cn"
# 版本
version: "1.0"
# 描述
description: "API 描述"
# swagger扫描的基础包,默认:全扫描
base-package: "cn.yunlingfly.springbootswaggerstarter.controller"
# 需要处理的基础URL规则,默认:/**
base-path: /**
# 需要排除的URL规则,默认:空
# exclude-path: ""
license: "Apache License, Version 2.0"
license-url: "https://www.apache.org/licenses/LICENSE-2.0.html"
然后application启动类添加一个@EnableSwagger2Doc注解即可,例如:
package cn.yunlingfly.springbootswaggerstarter;
import com.spring4all.swagger.EnableSwagger2Doc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableSwagger2Doc
public class SpringbootSwaggerStarterApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootSwaggerStarterApplication.class, args);
}
}
然后Controller层还是和以前一样用@Api、@ApiOperation、@ApiImplicitParam来写就行,ui还是访问http://localhost:8081/swagger-ui.html
如果报错java.lang.NumberFormatException:For input string:"",这是swagger2.9的问题,错在AbstractSerializableParameter这个类,解决方法请戳->Swagger2异常
更多参数配置->https://github.com/SpringForAll/spring-boot-starter-swagger#%E9%85%8D%E7%BD%AE%E7%A4%BA%E4%BE%8B