swagger是解决前后端对接问题的API框架,用它可以自动生成接口文档
- 准备工作
使用swagger之前需要导入两个依赖
• Springfox-swagger2
• swagger-springmvc
对应的依赖写法:
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- 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>
导入依赖后需要编写一个配置类
@Configuration //配置类
@EnableSwagger2// 开启Swagger2的自动配置
public class SwaggerConfig {
}
当我们什么都不配置时,启动项目,打开网址
访问测试 :http://localhost:8080/swagger-ui.html
会看到Swagger的默认界面
我们可以在配置类中自定义配置页面的各中信息,比如如下代码
- Swagger的实例Bean是Docket,所以可以通过配置Docket配置swagger
//配置docket以配置Swagger具体参数
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2);
}
- 要配置页面基本信息还需要配置一个apiInfo()属性
private ApiInfo apiInfo() {
Contact contact = new Contact("联系人名字", "http://xxx.xxx.com/联系人访问链接", "联系人邮箱");
return new ApiInfo(
"Swagger学习", // 标题
"学习演示如何配置Swagger", // 描述
"v1.0", // 版本
"http://terms.service.url/链接", // 组织链接
contact, // 联系人信息
"Apach 2.0 许可", // 许可
"许可链接", // 许可连接
new ArrayList<>()