TOC
经过之前的配置,应该就很容易了。引入依赖 + 配置 = 引入成功。
引入依赖
我这里用的是2.9.2版本Swagger2的官方依赖。
<!--swaggerApi-->
<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>
配置信息
在config包下新增配置文件Swagger2Config.class
具体配置
package com.demo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration//标识为一个配置文件
@EnableSwagger2//使用Swagger2
public class Swagger2Config {
//从配置文件中决定是否可用
@Value("${swagger2.enable}")
boolean enable ;
//Api显示的详细配置信息
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBootDemo01的API接口文档")//标题
.description("我的第一个SpringBoot整合Swagger2的项目")//接口文档描述
.termsOfServiceUrl("欢迎一起学习")//声明
//联系方式
.contact(new Contact("三文鱼", "www.baidu.com", "xxx@qq.com"))
.version("1.0.0")//版本
.build();
}
//创建一个RestApi的容器
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)//Swagger2文档
.apiInfo(apiInfo())//api的信息
.select()
//扫描策略 这里扫描demo下的所有包的接口
.apis(RequestHandlerSelectors.basePackage("com.demo")) //从哪个包下面开始扫描
//全路径匹配
.paths(PathSelectors.any())
.build()
.enable(enable)//是否可用
.globalOperationParameters(globalOperation());//全局属性设置
}
// 添加参数 主要是设置token
private List<Parameter> globalOperation(){
//添加head参数配置start
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
//第一个token为传参的key,第二个token为swagger页面显示的值
tokenPar.name("token")
.description("token")
.modelRef(new ModelRef("string"))//String类型
.parameterType("header")//给请求头设置token
.required(false)//非必须
.build();
pars.add(tokenPar.build());
return pars;
}
}
给接口配置扫描信息
还记得之前的Controller吗,要想里面的接口被扫描进去,就要加上Swagger2的注解。以UserController为例:
其他的注解大家自行了解即可。
在application.yml文件中添加启动标识
#Swagger2是否可用
swagger2:
enable: true
可用状态
禁用之后
高版本的问题
使用2.6.0以上的版本,可能出现以下报错:
Failed to start bean ‘documentationPluginsBootstrapper’
原因可以参考这个:(已解决)Failed to start bean ‘documentationPluginsBootstrapper’
我的做法是在application.yml里加入以下配置信息:
spring:
#设置高版本Swagger匹配策略
mvc:
pathmatch:
matching-strategy: ant_path_matcher
位置在这里