在SpringBoot项目中引入Swagger,让接口数据可视化,尤其适用于Restful API
本案例使用工具:IDEA
本案例GitHub地址:https://github.com/limenggen/springboot-swagger-demo
1、创建一个SpringBoot项目
- 项目结构
2、引入swagger依赖
pom.xml
- 引入swagger原生依赖:springfox-swagger2和springfox-swagger-ui
pom.xml 1
2
3
4
5
6
7
8
9
10
11<!-- 引入swagger2依赖-->
<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>- 相关依赖需要注意版本
- 本案例依赖版本:
- spring-boot-starter-web:2.3.4
- mybatis-spring-boot-starter:2.3.4
- springfox-swagger2:2.9.2
- springfox-swagger-ui:2.9.2
- lombok:1.18.12
3、修改配置文件
修改application.properties文件为application.yml
1 | server: |
4、新建一个swagger配置类
SwaggerConfig.java
1 | import org.springframework.context.annotation.Bean; |
5、添加实体类
User.java
- @ApiModel:描述返回对象的意义,用在返回对象类上
- ApiModelProperty:对象属性, 用在出入参数对象的字段上
User.java 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Date;
public class User {
private Integer id;
private String name;
private Boolean enable;
private Date updateTime;
}
6、创建Controller类
添加swagger、RestController注解
- @Api:协议集描述, 用于controller类上
- @ApiOperation:协议描述,用在controller的方法上
testController.java >folded 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58import com.morgan.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class testController {
private static Map<Integer, User> userMap;
static {
userMap = new ConcurrentHashMap<>();
User user = new User(100, "admin", true, new Date());
}
public List<User> list(){
return new ArrayList<>(userMap.values());
}
public User detail({ Integer id)
return userMap.get(id);
}
public User add({ User user)
if(user == null || user.getId() == null || StringUtils.isEmpty(user.getName()) || userMap.containsKey(user.getId())){
return null;
}
user.setUpdateTime(new Date());
userMap.put(user.getId(), user);
return user;
}
public Boolean delete({ Integer id)
if(userMap.containsKey(id)){
userMap.remove(id);
return true;
}
return false;
}
}
7、启动项目
项目访问地址:http://localhost:8081/swagger-ui.html
评论