一、什么是Swagger
Swagger是一个Restful规范和完整的框架,用于生成、描述、调用和可视化Restful风格的Web服务。在后端服务定义好参数格式以及方法,启动服务后网页即可访问接口信息文档 ,并且在网页端可进行接口测试。
二、依赖导入
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
三、Swagger配置
编写Swagger配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2 //开启Swagger
public class SwaggerConfig {
//配置Swagger的Docket的Bean实例
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())//配置上下文信息
.enable(true)//swagger是否生效
.select()//获取docket中的选择器
.apis(RequestHandlerSelectors.basePackage("com.markerhub.controller"))//设置扫描哪个包中的注解
// .apis(RequestHandlerSelectors.any()) // 扫描所有,项目中的所有接口都会被扫描到
// .apis(RequestHandlerSelectors.none()) // 不扫描接口
// .apis(RequestHandlerSelectors.withClassAnnotation(ResponseBody.class)) // 通过类上的注解扫描
// .apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class)) // 通过方法上的注解扫描
.paths(PathSelectors.any()) // 扫描所有,项目中的所有接口都会被扫描到
// .paths(PathSelectors.ant("/api/**")) // 通配符过滤
// .paths(PathSelectors.none()) // 不扫描接口
// .paths(PathSelectors.regex("/api/v[1-2]")) // 正则过滤
.build() //添加登录认证
}
private ApiInfo apiInfo(){
//作者信息
Contact contact = new Contact("作者名称","网址","邮箱");
return new ApiInfo("xxxxx",//文档标题
"",//文档描述
"1.0",//版本
"www.baidu.com",//团队信息
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>()
);
}
}
四、访问Swagger文档
配置完成后启动项目,输入网址http://127.0.0.1:8080/swagger-ui.html 就可以访问swagger页面 了。