Swagger主要方便了前后端接口对接,以前接口对接需要大量文档,而且修改接口,文档也要跟着修改,浪费了大量的时间,使用Swagger只需要修改注解就行了。
文章比较简单,主要是实践下。
首先创建springboot工程
因为我其他项目端口占用 修改端口为8083
创建一个测试类,其中注解@RestController标记在类上,表示该类处理http请求,并且返回json数据(和swagger无关,但是你欧http请求,所以必填,不然找不到)
@RequestMapping是一个非常常见的注解,他是一个用来处理地址映射请求的注解,可以用于方法或者类上进行以产生对应路径的。
如果用于类上,大多数是为了进行区分controller。用于方法上则是对方法进行注解以产生访问的路径。
随后运行启动类,在web界面查看springboot是否成功
成功
接下来看swagger
首先在pom文件中添加
<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>
配置swagger 一些属性,也可以在yml配置中直接配置,如下
package com.example.springboot.config;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 指定controller存放的目录路径
.apis(RequestHandlerSelectors.basePackage("com.example.springboot"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 文档标题
.title("DigAg")
// 文档描述
.description("https://github.com/Yuicon")
.termsOfServiceUrl("https://github.com/Yuicon")
.version("v1")
.build();
}
}
然后只需要进入swagger的web界面就能测试接口
@ApiOperation注解就是说明这个方法或者类的作用