SpringBoot之swagger
swagger是什么
1、是一款让你更好的书写API文档的规范且完整框架。
2、提供描述、生产、消费和可视化RESTful Web Service。
3、是由庞大工具集合支撑的形式化规范。这个集合涵盖了从终端用户接口、底层代码库到商业API管理的方方面面。
springboot集成swagger
<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>
配置swagger
创建一个类,标注上@Configuration、@EnableSwagger2注解并创建一个Docket对象。
swagger页面访问地址:http://llocalhost:端口号/swagger-ui.html
@Configuration
@EnableSwagger2
public class SwagerrConfiguration {
private static ApiInfo DEFAULT = null;
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2);
}
}
如下图表示swagger已经配置成功
信息配置
@Configuration
@EnableSwagger2
public class SwagerrConfiguration {
private static ApiInfo DEFAULT = null;
@Bean
public Docket docket(){
Contact DEFAULT_CONTACT = new Contact("姜兴", "http://www.baidu.com", "2465180091@qq.com");
DEFAULT = new ApiInfo(
"姜兴的开发接口",
"Api Documentation",
"V-1.0",
"http://www.baidu.com",
DEFAULT_CONTACT,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
return new Docket(DocumentationType.SWAGGER_2).apiInfo(DEFAULT)
}
}
结果图:
swagger配置接口
1、apis(RequestHandlerSelectors.basePackage(“com.example.demo2.controller”))//按照包名扫描
2、apis(RequestHandlerSelectors.any())全部扫面
3、apis(RequestHandlerSelectors.none())不扫面
4、paths(PathSelectors.ant(“controller”))//过滤指定包下的接口
@Configuration
@EnableSwagger2
public class SwagerrConfiguration {
private static ApiInfo DEFAULT = null;
@Bean
public Docket docket(){
Contact DEFAULT_CONTACT = new Contact("姜兴", "http://www.baidu.com", "2465180091@qq.com");
DEFAULT = new ApiInfo("姜兴的开发接口",
"Api Documentation",
"V-1.0",
"http://www.baidu.com",
DEFAULT_CONTACT,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(DEFAULT)
.select()
//.apis(RequestHandlerSelectors.basePackage("com.example.demo2.controller"))//按照包名扫描
//.apis(RequestHandlerSelectors.any())全部扫面
//.apis(RequestHandlerSelectors.none())不扫面
// .paths(PathSelectors.ant("controller"))//过滤指定包下的接口
.build();
}
}
swagger关闭
根据环境关闭swagger
@Configuration
@EnableSwagger2//开启swagger
public class SwagerrConfiguration {
private static ApiInfo DEFAULT = null;
@Bean//创建swagger实例
public Docket docket(Environment environment){
Contact DEFAULT_CONTACT = new Contact("姜兴", "http://www.baidu.com", "2465180091@qq.com");
DEFAULT = new ApiInfo("姜兴的开发接口",
"Api Documentation",
"V-1.0",
"http://www.baidu.com",
DEFAULT_CONTACT,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
Profiles profiles = Profiles.of("dev");//设置在那个环境下显示swagger,这里设置环境为dev时显示
boolean b = environment.acceptsProfiles(profiles);//判断是不是现在的环境是不是我们想要的环境
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(DEFAULT)
.enable(b)//配置swagger是否开启,如果为false则关闭swagger,默认为true
.select()
.build();
}
}
表示关闭swagger,如果有两个swgger,其中一个打开的,那么不会出现这个试图,而是只显示没有关闭的那个swagger.
swagge分组
简单来说就是创建多个docket,并用groupName(“name”)指明是谁的
@Configuration
@EnableSwagger2//开启swagger
public class SwagerrConfiguration {
private static ApiInfo DEFAULT = null;
@Bean//创建swagger实例
public Docket docket(Environment environment){
Contact DEFAULT_CONTACT = new Contact("姜兴", "http://www.baidu.com", "2465180091@qq.com");
DEFAULT = new ApiInfo("姜兴的开发接口",
"Api Documentation",
"V-1.0",
"http://www.baidu.com",
DEFAULT_CONTACT,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
Profiles profiles = Profiles.of("dev");//设置在那个环境下显示swagger
boolean b = environment.acceptsProfiles(profiles);//获得项目的环境
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(DEFAULT)
.groupName("姜兴")
.enable(b)//配置swagger是否开启,如果为false则关闭swagger,默认为true
.select()
.build();
}
@Bean//创建swagger实例
public Docket docket1(Environment environment){
Contact DEFAULT_CONTACT = new Contact("姜明轩", "http://www.baidu.com", "2465180091@qq.com");
DEFAULT = new ApiInfo("姜明轩开发接口",
"Api Documentation",
"V-1.0",
"http://www.baidu.com",
DEFAULT_CONTACT,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
Profiles profiles = Profiles.of("dev");//设置在那个环境下显示swagger
boolean b = environment.acceptsProfiles(profiles);//获得项目的环境
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(DEFAULT)
.groupName("姜明轩")
.enable(b)//配置swagger是否开启,如果为false则关闭swagger,默认为true
.select()
.build();
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
swagger注解
swagger2 的注解其实就是给页面上的单词进行翻译,没有实际用处,了解即可。
1,swagger2 注解整体说明
用于 controller 类上:
注解 | 说明 |
---|---|
@Api | 对请求类的说明 |
用于方法上面 (说明参数的含义):
注解 | 说明 |
---|---|
@ApiOperation | 方法的说明 |
@ApiImplicitParams、@ApiImplicitParam | 方法的参数的说明;@ApiImplicitParams 用于指定单个参数的说明 |
用于方法上面 (返回参数或对象的说明):
注解 | 说明 |
---|---|
@ApiResponses、@ApiResponse | 方法返回值的说明 ;@ApiResponses 用于指定单个参数的说明 |
对象类:
注解 | 说明 |
---|---|
@ApiModel | 用在 JavaBean 类上,说明 JavaBean 的 用途 |
@ApiModelProperty | 用在 JavaBean 类的属性上面,说明此属性的的含议 |
2,@API: 请求类的说明
@API: 放在 请求的类上, 与 @Controller 并列, 说明类的作用, 如用户模块, 订单类等.
tags="说明该类的作用" value="该参数没什么意义, 所以不需要配置"
示例:
@API(tags="订单模块")@Controllerpublic class OrderController { }
@API 其它属性配置:
属性名称 | 备注 |
---|---|
value | url 的路径值 |
tags | 如果设置这个值、value 的值会被覆盖 |
description | 对 api 资源的描述 |
basePath | 基本路径 |
position | 如果配置多个 Api 想改变显示的顺序位置 |
---|---|
produces | 如, “application/json, application/xml” |
consumes | 如, “application/json, application/xml” |
protocols | 协议类型,如: http, https, ws, wss. |
---|---|
authorizations | 高级特性认证时配置 |
hidden | 配置为 true ,将在文档中隐藏 |
3,@ApiOperation: 方法的说明
@ApiOperation:"用在请求的方法上, 说明方法的作用" value="说明方法的作用" notes="方法的备注说明"
3.1,@ApiImplicitParams,@ApiImplicitParam: 方法参数的说明
@ApiImplicitParams: 用在请求的方法上, 包含一组参数说明
@ApiImplicitParam: 对单个参数的说明
name: 参数名
value: 参数的汉字说明, 解释
required: 参数是否必须传
paramType: 参数放在哪个地方
. header --> 请求参数的获取:@RequestHeader
. query --> 请求参数的获取:@RequestParam
. path(用于 restful 接口)–> 请求参数的获取:@PathVariable
. body(请求体)--> @RequestBody User user . form(普通表单提交)
dataType: 参数类型, 默认 String, 其它值 dataType=“Integer”
defaultValue: 参数的默认值
示列:
@API(tags="用户模块")
@Controller
public class UserController {
@ApiOperation(value="用户登录",notes="随边说点啥")
@ApiImplicitParams({
@ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
@ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
@ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="Integer")
})
@PostMapping("/login")
public JsonResult login(@RequestParam String mobile, @RequestParam String password,
@RequestParam Integer age){
//...
return JsonResult.ok(map);
}
}
4,@ApiResponses,@ApiResponse: 方法返回值的说明
@ApiResponses: 方法返回对象的说明
@ApiResponse: 每个参数的说明
code: 数字, 例如 400
message: 信息, 例如 “请求参数没填好”
response: 抛出异常的类
示例:
@API(tags="用户模块")
@Controller
public class UserController {
@ApiOperation("获取用户信息")
@ApiImplicitParams({
@ApiImplicitParam(paramType="query", name="userId", dataType="String", required=true, value="用户 Id")
})
@ApiResponses({
@ApiResponse(code = 400, message = "请求参数没填好"),
@ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
})
@ResponseBody
@RequestMapping("/list")
public JsonResult list(@RequestParam String userId) {
...
return JsonResult.ok().put("page", pageUtil);
}
}
5,@ApiModel: 用于 JavaBean 上面, 表示一个 JavaBean(如: 响应数据) 的信息
@ApiModel: 用于 JavaBean 的类上面, 表示此 JavaBean 整体的信息
(这种一般用在 post 创建的时候, 使用 @RequestBody 这样的场景,
请求参数无法使用 @ApiImplicitParam 注解进行描述的时候 )
5.1,@ApiModelProperty: 用在 JavaBean 类的属性上面, 说明属性的含义
示例:
@ApiModel(description= "返回响应数据")
public class RestMessage implements Serializable{
@ApiModelProperty(value = "是否成功")
private boolean success=true;
@ApiModelProperty(value = "返回对象")
private Object data;
@ApiModelProperty(value = "错误编号")
private Integer errCode;
@ApiModelProperty(value = "错误信息")
private String message;
/* getter/setter 略 */
}
(swageer注解文档来源于http://www.bubuko.com/infodetail-3289545.html)
示例图片:
swgger测试
点击测试
输入这个请求需要的参数,并执行
可以看到各种信息及其返回数据格式
扩展
https://github.com/caspar-chen/swagger-ui-layer
1、导入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.caspar-chen</groupId>
<artifactId>swagger-ui-layer</artifactId>
<version>1.1.3</version>
</dependency>
2、添加swagger功能和注解
启用swagger ,创建SwaggerConfig文件,内容如下,
需要注意的一点是 swagger api 的默认地址是
/v2/api-docs
所以swagger-ui-layer也读取的是默认地址, 所以在new Docket()的时候不能指定group参数,否则 swagger api 的地址会在后面加入group的参数导致swagger-ui-layer不能正确请求到数据
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket ProductApi() {
return new Docket(DocumentationType.SWAGGER_2)
.genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(false)
.pathMapping("/")
.select()
.build()
.apiInfo(productApiInfo());
}
private ApiInfo productApiInfo() {
ApiInfo apiInfo = new ApiInfo("XXX系统数据接口文档",
"文档描述。。。",
"1.0.0",
"API TERMS URL",
"联系人邮箱",
"license",
"license url");
return apiInfo;
}
}
常用的swagger注解 Api ApiModel ApiModelProperty ApiOperation ApiParam ApiResponse ApiResponses ResponseHeader
3、查看结果
swagger-ui-layer的默认访问地址是
http://
h
o
s
t
:
{host}:
host:{port}/docs.html