springboot 集成 swagger2,配置类
具体步骤:
1,引入 jar 包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2,编写 configuration 类
package com.xxx.common.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
/**
* Swagger2配置
* eg: http://localhost:8090/swagger-ui.html
* @date 2018/5/3 10:52
* @since
* @param
*/
@Configuration
// @ConditionalOnProperty(prefix = "swagger", value = { "enable" }, havingValue = "true") // 是否启用该 config
// @Profile{"dev, local"}
@EnableSwagger2
public class Swagger2Configuration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()) // 基本信息
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.test.controller")) // 指定扫描的包
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("xxx系统-xxx服务 RESTful APIs")
.description("xxx服务后台api接口文档")
.contact(new Contact("xxx", null, "xxx@qq.com"))
.version("1.0")
.build();
}
}
3,常用的注解介绍与使用
3.1,swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。
@Api() 用于类;表示标识这个类是swagger的资源
tags–表示说明
value–也是说明,可以使用tags替代
@ApiOperation() 用于方法;表示一个http请求的操作
value用于方法描述
notes用于提示内容
tags可以重新分组(视情况而用)
@ApiParam() 用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等)
name–参数名
value–参数说明
required–是否必填
@ApiIgnore()用于类或者方法上,可以不被swagger显示在页面上
示例:
@Api(value="用户controller",tags={"用户操作接口"})
@RestController
public class UserController {
@ApiOperation(value="获取用户信息",tags={"获取用户信息copy"},notes="注意问题点")
@GetMapping("/getUserInfo")
public User getUserInfo(@ApiParam(name="id",value="用户id",required=true) Long id,@ApiParam(name="username",value="用户名") String username) {
// userService可忽略,是业务逻辑
User user = userService.getUserInfo();
return user;
}
@ApiIgnore//使用该注解忽略这个API
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String jsonTest() {
return " hi you!";
}
}
@ApiModel()用于类 ;表示对类进行说明,用于参数用实体类接收
value–表示对象名
description–描述
都可省略
@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
示例:
@ApiModel(value="user对象",description="用户对象user")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
@ApiModelProperty(value="用户名",name="username",example="xingguo")
private String username;
@ApiModelProperty(value="状态",name="state",required=true)
private Integer state;
private String password;
private String nickName;
private Integer isDeleted;
@ApiModelProperty(value="id数组",hidden=true)
private String[] ids;
private List<String> idList;
//省略get/set
}
@ApiOperation("更改用户信息")
@PostMapping("/updateUserInfo")
public int updateUserInfo(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) User user){
int num = userService.updateUserInfo(user);
return num;
}
@ApiImplicitParam() 用于方法
表示单独的请求参数
@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
name–参数ming
value–参数说明
dataType–数据类型
paramType–参数类型
示例:
@ApiOperation("查询测试")
@GetMapping("select")
//@ApiImplicitParam(name="name",value="用户名",dataType="String", paramType = "query")
@ApiImplicitParams({
@ApiImplicitParam(name="name",value="用户名",dataType="string", paramType = "query",example="xingguo"),
@ApiImplicitParam(name="id",value="用户id",dataType="long", paramType = "query")})
public void select(){
}
4,访问 swagger2 的 UI 界面
4.1,默认的 UI 界面访问地址
swagger2 的 UI 地址默认使用 http://youIp:port/swagger-ui.html 来访问
4.2,自定义 swagger2 UI 访问地址
如想要自定义访问路径,按照此博客步骤操作即可:https://blog.youkuaiyun.com/u012954706/article/details/81086244
如下图所示:
5,安全起见,生产环境应当关闭swagger文档
可以通过以下两种方式进行关闭:
5.1,使用 @ConditionalOnProperty 注解
1. 在 swagger 的配置类上增加 @ConditionalOnProperty(prefix = "swagger", value = { "enable" }, havingValue = "true") 注解
2. 在 application.yml 或者 application.properties 文件中增加如下配置
swagger.enable=false # 关闭
swagger.enable=true # 开启
5.2,使用 @Profile 注解
1. 在 swagger 配置类上增加 @Profile{"dev, local"} 注解,注解中指定的是开启 swagger2 UI 界面的环境,这里指定的是本地和开发环境
2. 配置多套环境的 application.properties 文件,在主配置文件中指定使用的环境
spring.profiles.active=local
# spring.profiles.active=prod
关闭时展示的页面,如下图所示:
6,使用 zuul + Swagger 实现管理整个微服务 API 接口文档
只需要 zuul 网关,添加对应服务 swagger 文档即可
6.2 单个服务中
1,添加依赖
一下依赖已经包括了单个服务添加 swagger 的两个依赖,并且不需要在单独配置 swaggerConfig 文件,直接在 yml 文件中配置即可
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
2,在启动类中添加注解支持
@EnableDiscoveryClient
@SpringBootApplication
@EnableSwagger2Doc
public class EurekaClientDemo01Application {
public static void main(String[] args) {
SpringApplication.run(EurekaClientDemo01Application.class, args);
}
}
3,配置 yml 文件
指定扫包的路径
swagger:
base-package: com.example.eurekaclientdemo01.controller
4,单个访问 swagger-UI 界面
http://localhost:8086/swagger-ui.html
这里可以选择查看哪个服务的 swagger api 文档
6.3 在 zuul 中集成 swagger
1,添加依赖
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
2,在 zuul 中添加文档来源、
package com.example.zuuldemo.config;
import com.spring4all.swagger.EnableSwagger2Doc;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.ArrayList;
import java.util.List;
/**
* 添加文档来源
*/
@Configuration
@EnableSwagger2Doc
@Component
@Primary
public class Swagger2Config implements SwaggerResourcesProvider {
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resource = new ArrayList();
resource.add(swaggerResource("eureka-client-demo", "/user-service/v2/api-docs", "2.0"));
resource.add(swaggerResource("eureka-client-demo-03", "order-service/v2/api-docs", "2.0"));
return resource;
}
/**
* @param name 名称可以自定义
* @param location /user-service/ 这一段配置需要和 yml 文件中路由转发配置的 path: 路径保持一致
* @param version 使用的版本
* @return
*/
private SwaggerResource swaggerResource(String name, String location, String version) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion(version);
return swaggerResource;
}
}
注意:使用 zuul + swagger 集成时,使用的 jar 包依赖要保持一致