前后端集成联调,前端人员和后端人员无法做到 "即时协商",后端提供接口,需要实时更新最新的消息以及改动。
- 通过Swagger给一些属性提供注释
- 接口文档实时更新
- 提供在线测试功能
- 出于安全考虑,在正式上线时关闭swagger,同时可以节省内存
官网:https://swagger.io/,导入依赖
<dependency>
<groupId>io.github.wilson-he</groupId>
<artifactId>swagger2-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
Swagger自定义配置
以下配置在导入swagger2-spring-boot-starter后,可以通过查看SwaggerAutoConfiguration,在yaml文件中实现自动配置,因此了解即可。
package com.strtz3.blog.config.custom;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2).
apiInfo(apiInfo())
.select() .apis(RequestHandlerSelectors.basePackage("com.strtz3.blog.controller.admin"))
//any() 扫描全部
//none()不扫描
//basePackage() 扫描指定包
//withMethodAnnotation() 扫描方法上的指定注解
//withClassAnnotation 扫描类上的指定注解
.build();
}
public ApiInfo apiInfo() {
return new ApiInfo("Swagger Api 文档",
"Api document description",
"1.0",
"https://wwww.baidu.com", //team组织
new Contact("联系人姓名", "联系人url", "联系人邮箱"),
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<VendorExtension>());
}
}
Swagger分组
每个组都是一个独立的swagger
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("a");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("b");
}
@Bean
public Docket docket3(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("c");
}
如果希望swagger只在生产环境使用,在发布环境中不起作用,需要怎么做呢?
配置类配置:
/**
* 传入spring容器的environment,根据启动环境判断是否开启swagger
* @param environment
* @return
*/
@Bean
public Docket docket(Environment environment) {
//设置swagger启动的环境
Profiles profiles = Profiles.of("dev", "test");
//判断是否处于以下开发环境
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2).
apiInfo(apiInfo())
.enable(flag); //swagger开关
}
yaml配置:
操作控制中,发现swagger.profile直接指定运行环境无效,原因未知;因此采用了第二种方法:在dev开启swagger,prod设置关闭swagger
#swagger
swagger:
docket:
api-info:
title: 个人博客文档
contact:
name: strtz3
email: strtz3@163.com
version: 1.0
group-name: strtz3
base-package: com.strtz3.blog.controller
swagger:
enabled: true
常用注解
只要返回值中存在实体类,Models就会返回实体类信息。
描述 | |
---|---|
@ApiModel | 描述类 |
@ApiModelProperty | 描述属性 |
@ApiOperation | 描述方法 |
@ApiParam | 描述参数 |