Swagger
Swagger是一种可以帮助我们简化 API 开发过程的工具
快速开始
第一步:创建Spring Boot项目并且在pom.xml中引入Swagger的依赖包,Maven坐标如下:
<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>
第二步:创建Swagger配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* 将Docket对象交给Spring容器管理
* Docket是Swagger的全局配置对象
* select() 返回 ApiSelectorBuilder对象,控制包扫描,Api文档生成的路径等
*
* @return Swagger的全局配置对象
*/
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
// Api基本信息
.apiInfo(apiInfo())
// 分组名称
.groupName("admin")
.select()
// Swagger扫描的包及其子包
.apis(RequestHandlerSelectors.basePackage("com.sin"))
// Swagger会生成Api文档的路径
.paths(PathSelectors.any())
.build();
}
/**
* Api基本信息配置
*
* @return API详细信息
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 标题
.title("Swagger 接口文档的标题")
// 详细描述
.description("Swagger API详细信息的描述")
// 团队服务地址
.termsOfServiceUrl("xxx")
// 版本号
.version("1.0")
// contact(作者名,url地址,email地址)
.contact(new Contact(
"作者名",
"https://xxx",
"xxx@qq.com"))
.build();
}
}
第三步:新建一个接口UserController类
@Api(tags = "用户接口")
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@ApiOperation("查询用户")
@GetMapping("/{id}")
public UserDTO getAllUser(@PathVariable("id") Integer id) {
return userService.getById(id);
}
@ApiOperation("添加用户")
@RequestMapping(method = RequestMethod.POST)
public Boolean saveUser(@RequestBody UserDTO userDTO) {
return userService.save(userDTO);
}
@ApiOperation("删除用户")
@DeleteMapping("/{id}")
public Boolean deleteUser(@PathVariable Integer id) {
return userService.removeById(id);
}
@ApiOperation("修改用户")
@RequestMapping(method = RequestMethod.PUT)
public Boolean modifyUser(@RequestBody UserDTO userDTO) {
return userService.modifyUser(userDTO);
}
}
第四步:新建一个实体类UserDTO
@Data
@ApiModel("用户 DTO")
public class UserDTO {
@ApiModelProperty("用户id")
private Integer id;
@ApiModelProperty("用户名")
private String username;
@ApiModelProperty("密码")
private String password;
}
第五步:访问地址,查看接口文档
http://localhost:8080/swagger-ui.html
常用注解
| 注解 | 作用 |
|---|---|
| @Api | 用在类上,说明该类的作用 |
| @ApiOperation | 作用在方法上,说明方法的作用 |
| @ApiImplicitParam | 作用在方法上,给方法参数添加说明 |
| @ApiImplicitParams | 用在方法上包含一组参数说明 |
| @ApiModel | 描述一个Model的信息 |
| @ApiModelProperty | 描述一个Model的属性 |
具体使用参考文末其他链接
美化UI
使用knife4j来美化Swagger的ui界面
在maven中添加依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-ui</artifactId>
<version>3.0.3</version>
</dependency>
访问地址
http://localhost:8080/doc.html
参考链接
慕课教程:www.imooc.com/wiki/swagge…
Swagger ui优化:github.com/xiaoymin/sw…
knife4j:www.xiaominfo.com/