swagger配置和简单使⽤
说明:本地环境idea + maven3.5 + springboot2.0.0 + springfox-swagger2 2.8.0 + springfox-swagger-ui 2.8.0 + swagger-bootstrap-ui 1.7.2(为了展⽰的更好看)
1 搭建完Springboot 项⽬后在pom⽂件中添加依赖
<springfox-swagger.version>2.8.0</springfox-swagger.version>
<swagger-bootstrap-ui.version>1.7.2</swagger-bootstrap-ui.version>
<!-- mvnrepository/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-swagger.version}</version>
</dependency>
<!-- mvnrepository/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-swagger.version}</version>
</dependency>
<!-- mvnrepository/artifact/com.github.xiaoymin/swagger-bootstrap-ui -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>${swagger-bootstrap-ui.version}</version>
</dependency>
2 创建配置类 SwaggerConfig
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket petApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.huitong")) //指定提供接⼝所在的基包
.
build();
}
/**
* 该套 API 说明,包含作者、简介、版本、host、服务URL
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("demo api 说明")
.contact(new Contact("allen","null","name@example"))
.version("0.1")
.
termsOfServiceUrl("localhost:8080/demo1/")
.description("demo api")
.build();
}
}
3 对接⼝和实体类添加注释,⽣成doc。常⽤的标记如下
@Api()⽤于类;
标识这个类是swagger的资源
tags–表⽰分组说明标签
@ApiOperation()⽤于⽅法;
表⽰⼀个http请求的操作
value⽤于⽅法描述
notes⽤于提⽰内容
@ApiModel()⽤于实体类
表⽰对类进⾏说明,⽤于参数⽤实体类接收
value–表⽰对象名
description–描述
@ApiModelProperty()⽤于实体类字段
表⽰对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字bootstrap项目
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
@ApiImplicitParam() ⽤于 controller ⽅法
表⽰单独的请求参数
name–参数ming
value–参数说明
dataType–数据类型
paramType–参数类型
example–举例说明
@ApiImplicitParams() ⽤于 controller ⽅法,包含多个 @ApiImplicitParam
@ApiIgnore()⽤于类或者⽅法上,可以不被swagger显⽰在页⾯上
说明:简单的标记只需要@Api(tags="") 和 @ApiOperation(value="",notes="")
更多关于注解⽤法可以参考github/swagger-api/swagger-core/wiki/Annotations
4 搭建完成后可以测试⼀波了。启动服务,在浏览器中输⼊ localhost:8080/swagger-ui.html ,界⾯如下
在浏览器中输⼊ localhost:8080/doc.html
从中可以看出,swagger 适合作为简单的 API ⽂档,并进⾏简单测试。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论