1.引入依賴
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
2.在 application.yml 中進(jìn)行配置
swagger:
base-path: /**
base-package: 'com.example.demo'
title: 'spring-boot-swagger-demo'
description: '基于Swagger構(gòu)建的SpringBoot RESTApi 文檔'
version: '1.0'
contact:
name: '空夜'
url: 'http://www.eknown.cn'
email: 'eknown@163.com'
3.在啟動(dòng)類上添加注解 @EnableSwagger2
4.在 controller 層添加注解
@Api(tags = "用戶管理")
@RestController
@RequestMapping("api/user")
public class UserController extends BaseController {
private static final Logger LOG = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
//查看所有
@ApiOperation("查看所有用戶")
@GetMapping("findAll")
public RestResponse findAll() {
return success(userService.findAll());
}
//根據(jù)id查看
@ApiOperation("根據(jù)用戶 id 查看用戶")
@GetMapping("findById")
public RestResponse findById(@RequestParam(name = "id") Integer id) {
try {
List<User> user = userService.findById(id);
if (user.size() == 0) {
return notFound("The data does not exist");
}
return success(user);
} catch (Exception e) {
LOG.error("Get user error.", e);
return error("GET USER INFORMATION FAILED!");
}
}
5.在實(shí)體層添加注解
@ApiModel(description = "用戶類")
@Table(name = "user")
public class User {
@Id
@KeySql(useGeneratedKeys = true)
private Integer id;
@ApiModelProperty(value = "用戶名")
private String name ;
private Integer age;
private String email;
最后訪問(wèn) :http://localhost:8888/swagger-ui.html