1.引入依赖
- 这里用的是2.7.0版本
<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>
- 上线的时候可能需要找到所有依赖的jar包,如下图

2.swagger配置类
@Configuration
@EnableSwagger2
public class Swagger2 {
/**
* 创建API应用
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 本例采用指定扫描的包路径来定义指定要建立API的目录。
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("cn.wx.swagger"))//配置扫描的包路径
.paths(PathSelectors.any())
.build();
}
/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://项目实际地址/swagger-ui.html
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("这是标题- API文档")//标题
.description(" 此处填写标题描述~~~~~~~~~~~~~~~")//标题描述
.termsOfServiceUrl("https://www.baidu.com")
.contact("LYC")//创建者
.version("1.0")//版本
.build();
}
}

3.接口使用相关注解示例
- @API :用在类上,标识这个类是swagger的资源
value:
description:接口描述


- @ApiOperation:注解来给API增加方法说明。
value:方法描述
notes:提示信息


- @ApiImplicitParams : 用在方法上包含一组参数说明。
@RequestMapping(value = "/byname", method = RequestMethod.GET)
@ResponseBody
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query",name= "username" ,value = "用户名",dataType = "string",required = true,defaultValue = "张三"),
@ApiImplicitParam(paramType = "query",name= "age" ,value = "年龄",dataType = "int",required = true),
@ApiImplicitParam(paramType = "query",name= "address" ,value = "地址",dataType = "string",required = true)
})
@ApiOperation(value = "通过用户名获取用户信息", notes="返回用户信息")
public ResponseEntity<StuUser> getUserByUserName(HttpServletRequest request, String username, Integer age, String address) {
StuUser stuUser = new StuUser();
stuUser.setAddress(address);
stuUser.setAge(age);
stuUser.setName(username);
return new ResponseEntity<StuUser>(stuUser, HttpStatus.OK);
}

- @ApiImplicitParam:用来注解来给方法入参增加说明。
| paramType:指定参数放在哪个地方 | header:请求参数放置于Request Header,使用@RequestHeader获取 query:请求参数放置于请求地址,使用@RequestParam获取 path:以地址的形式提交数据,请求参数的获取:@PathVariable body:以流的形式提交,仅支持POST(不常用) form:以form表单的形式提交,仅支持post(不常用) |
|---|---|
| name:参数名 | |
| value:说明参数的描述 | |
| dataType:参数类型 | 只做标志说明 |
| required:参数是否必须传 | true或false |
| defaultValue:参数的默认值 |
- @ApiResponses:用于表示一组响应


- @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
l code:数字,例如400
l message:信息,例如"请求参数没填好"
l response:抛出异常的类 - @ApiModel:用于类,表示对类进行说明,用于参数用实体类接收;
@ApiModelProperty:用于方法,字段 ,表示对model属性的说明或者数据操作更改


4.访问方式
访问地址:http://项目实际地址/swagger-ui.html
本文详细介绍如何在Spring Boot项目中使用Swagger2生成RESTful API文档。从依赖引入到配置类编写,再到接口注解使用,最后展示访问方式,帮助开发者快速上手。
1万+

被折叠的 条评论
为什么被折叠?



