使用swagger自动生成html文档

使用swagger自动生成html文档

使用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
--启动类添加注解--
@EnableSwagger2

--添加依赖--
<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>

启动后访问地址
http://localhost:8060/swagger-ui.html

swagger 常用注解

  • @ApiOperation(value = "用户查询服务") 标记方法名
1
2
3
@ApiOperation(value = "用户查询服务")
public List<User> query(@RequestParam String username){
}
  • @ApiModelProperty(value = "年龄") 标记在元素上,表名该元素作用
1
2
@ApiModelProperty(value = "年龄")
private int age;
  • @ApiParam("用户id") 标记在方法的请求参数上
1
public User getInfo(@ApiParam("用户id") @PathVariable String id) {}

SpringBoot集成Swagger2中遇到的问题

Spring Boot自动配置本身不会自动把/swagger-ui.html这个路径映射到对应的目录META-INF/resources/下面。我们加上这个映射即可。代码如下:

1
2
3
4
5
6
7
8
9
10
11
@Configuration
class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/")

registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
}
}

同时,在启动类上添加注解@EnableWebMvc。
当然,为了更加方便使用SpringBoot集成swagger,这个工作可以直接通过定制swagger-starter来完成。

使用WireMock快速伪造RESTful服务

使用方法

  1. 添加依赖
1
2
3
4
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
</dependency>
  1. 下载jar运行
1
http://wiremock.org/
#
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×