您的位置:首页 > 编程语言 > Java开发

swagger ui和spring boot集成生成api文档

2017-03-15 00:00 309 查看
摘要: 在项目开发中使用了Spring boot与swagger的集成生成了api文档,但是由于对swagger的接触不是很深,没有弄清楚相关注解,就比如说类上面的注解,以及实体上面的注解。最终在网上发现了这篇博文,也解决了我遇到的问题“如何在类名上面添加注解”

swagger ui和spring boot集成生成api文档

原文链接:swagger ui和spring boot集成生成api文档

效果图



环境

JAVA8

MAVEN 3.0.5

IDEA 2016.2.5

spring boot 1.4.1

相关依赖

POM.xml

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>

配置

设置了一些默认显示的api相关信息,最后上截图的时就可以比较清楚的看到

Swagger2Config.java

@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("info.xiaomo.website"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("api根地址:http://api.xiaomo.info:8080/")
.termsOfServiceUrl("https://xiaomo.info/")
.contact("小莫")
.version("1.0")
.build();
}
}

相关注解解读

@Api

用在类上,说明该类的作用

@Api(value = "UserController", description = "用户相关api")


@ApiOperation

用在方法上,说明方法的作用

@ApiOperation(value = "查找用户", notes = "查找用户", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)


@ApiImplicitParams

用在方法上包含一组参数说明

@ApiImplicitParam

用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
paramType:参数放在哪个地方
header–>请求参数的获取:@RequestHeader
query–>请求参数的获取:@RequestParam
path(用于restful接口)–>请求参数的获取:@PathVariable
body(不常用)
form(不常用)
name:参数名
dataType:参数类型
required:参数是否必须传
value:参数的意思
defaultValue:参数的默认值

@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path"),
})


@ApiResponses

用于表示一组响应

@ApiResponse

用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如”请求参数没填好”
response:抛出异常的类

@ApiResponses(value = {
@ApiResponse(code = 400, message = "No Name Provided")
})


@ApiModel

描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用> @ApiImplicitParam注解进行描述的时候)

@ApiModel(value = "用户实体类")


@ApiModelProperty

描述一个model的属性

@ApiModelProperty(value = "登录用户")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息