之前测试接口一直使用postman在测试,后来发现postman还是不太方便,需要自己输入接口地址和接口参数。后来发现了swagger2,超级好用,只需要在你的接口那里加上swagger的相关注解,他就会自己给你生成接口文档,可以在上面测试,也不用像postman那样自己输入接口地址和参数了。这里记录一下在springboot项目上的集成过程,还是比较简单方便的。
1、在pom.xml文件中引入swagger的相关包
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2、编写swagger启动配置类。 Tips:swagger默认是不自定义head参数的,但是项目里有用到token,通过globalOperationParameters这里设置了headers请求参数。如果不需要headers,globalOperationParameters这部分相关可以去掉
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.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
public class SwaggerConfiguration {
@Bean
public Docket createRestApi() {
//增加请求头参数
ParameterBuilder tokenParams1 = new ParameterBuilder();
ParameterBuilder tokenParams2 = new ParameterBuilder();
List<Parameter> params = new ArrayList<Parameter>();
tokenParams1.name("token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
tokenParams2.name("loginName").description("登录账号").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
params.add(tokenParams1.build());
params.add(tokenParams2.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(params);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("xxx接口文档")
.description("接口文档")
.version("1.0")
.build();
}
}
3、编写接口,使用@Api、@ApiOperation等相关注解,即可在swagger文档上进行访问测试。
4、swagger接口文档地址:http://localhost:8080/swagger-ui.html
点击Try it out按钮,就可以输入相关的参数值进行测试啦