作者Gitee地址 https://gitee.com/thciweicloud
作者项目 面包博客,一个微服务架构的前后端分离博客系统。
整合Swagger2
- pom.xml
添加两个依赖
<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>
- 配置 config 注意提交 Bean
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.thciwei.swagger2.controller"))
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.description("接口文档的详细描述信息")
//文档名
.title("项目接口文档")
.contact(new Contact("thciwei", "http://www.thciwei.com",
"1462106316@qq.com"))
.version("v1.0")
.license("Apache2.0")
//这里还可以添加你的开源协议
.build());
}
}
- 创建实体类 User
@Data
//给实体类添加中文注释
@ApiModel(value = "用户实体类",description = "用户详细信息描述")
public class User {
@ApiModelProperty(value = "用户id")
private Integer id;
@ApiModelProperty(value = "用户名")
private String username;
}
- 接口描述
我们的swagger2 支持在页面中对接口进行测试
@Api(tags = “xx”) 接口总标签
@ApiOperation(value = “xx”, notes = “xx”) 接口方法描述
@ApiImplicitParam(name = “xx”, value = “xxxx”, required = true/false,defaultValue = “99”) 接口参数说明(代码字段名称,字段说明,是否必填,默认值)
@ApiResponses({
@ApiResponse(code = xxx, message = “xx”),
@ApiResponse(code = xxx, message = “xx”) }) 设置接口响应值和内容
@ApiIgnore 不生产接口文档
@RestController
@Api(tags = "用户数据接口")
public class UserController {
@ApiOperation(value = "查询用户", notes = "根据用户id查询用户")
@ApiImplicitParam(name = "id", value = "用户id", required = true)
//真正必填要在方法中 requestParams id
@GetMapping("/user")
public User getUserById(Integer id) {
User user = new User();
user.setId(id);
user.setUsername("thciwei");
return user;
}
@ApiOperation(value = "查询用户", notes = "根据用户id查询用户")
@ApiImplicitParam(name = "id", value = "用户id", required = true, defaultValue = "99")
@ApiResponses({
@ApiResponse(code = 500, message = "删除失败"),
@ApiResponse(code = 200, message = "删除成功")
})
@DeleteMapping("/user/{id}")
public void deleteById(@PathVariable("id") Integer id) {
System.out.println("delete" + id);
}
@ApiOperation(value = "更新用户", notes = "根据用户id更新用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户id", required = true, defaultValue = "99"),
@ApiImplicitParam(name = "username", value = "用户名", required = true, defaultValue = "thciwei")
})
@ApiResponses({
@ApiResponse(code = 500, message = "删除失败"),
@ApiResponse(code = 200, message = "删除成功")
})
//忽略
@ApiIgnore
@PutMapping("/")
public void updateUser(String name, Integer id) {
User user = new User();
user.setUsername("thciwei");
user.setId(1);
}
@PostMapping("/user")
@ApiOperation(value = "添加用户", notes = "添加用户接口")
//给参数一个具体的描述,在实体类中操作
public User addUser(@RequestBody User user) {
return user;
}
}
- 访问页面
localhost:8080/swagger-ui.html