是什么
Swagger可以根据项目代码自动生成相应的api文档,协调前后端分离中个模块的开发。
怎么做
1、引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
<scope>provided </scope>
</dependency>
2、文件配置
在springboot项目中新建一个SwaggerConfig类用于配置。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket webApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("dev01")
.apiInfo(webApiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("Swagger入门测试")
.description("信息管理系统接口定义")
.version("1.0")
.contact(new Contact("JARVIS", "http://127.0.0.1:8080/swagger-ui.html", ""))
.build();
}
}
3、添加注解
实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "User",description = "用户对象")
@TableName(value = "t_user")
public class User {
@TableId(type = IdType.AUTO)
@ApiModelProperty("用户ID")
private Long id;
@ApiModelProperty("用户姓名")
private String name;
@ApiModelProperty("用户年龄")
private Integer age;
@ApiModelProperty("用户邮箱")
private String email;
}
Controller
@RestController
@Api(value = "用户管理",tags = "用户管理")
public class UserController {
@Autowired
private UserService userService;
/**
* 分页查询
* @return
*/
@ApiOperation("分页查询用户信息")
@GetMapping("page/{page}/{size}")
public List<User> selectPage(
@ApiParam(name = "page",value = "当前第几页",required = true) @PathVariable Integer page,
@ApiParam(name = "size",value = "每页显示数据条数",required = true) @PathVariable Integer size){
// Page参数 current ==> 当前第几页 size ==> 查询的数据条数
Page page1 = new Page(page,size);
List<User> list = userService.selectPage(page1, null);
return list;
}
@ApiOperation("根据id查询用户")
@GetMapping("user/{id}")
public User getUserById(@ApiParam(name = "id",value = "用户id",required = true) @PathVariable Integer id){
User user = userService.selectById(id);
return user;
}
}
4、启动项目
访问 http:127.0.0.1:8080/swagger-ui.html 即可。
下面说明分页查询 /page/{page}/{size}接口的测试。