SpringBoot整合swagger实现测试Restful风格api
这篇文章运用了实例代码展示SpringBoot整合swagger实现测试Restful风格api的步骤,代码非常详细,可供感兴趣的小伙伴们参考借鉴,希望对大家有所帮助。
一.Restful 风格APIrestful API 命名禁止出现动词,即用请求方式区分动作。如下:
get 查询接口post 新增接口put 更新接口delete 删除接口
1.maven-archetype-quickstart方式创建模块springboot-restful-api2.把springboot-ssm模块的代码和配置复制过来,不需要额外引入依赖。3.修改UserController代码,改成Restful接口
@RestController@RequestMapping("/user")public class UserController { @Resource private UserMapper userMapper; //@RequestMapping("/listByUser") @GetMapping("/") public List<User> listByUser() { return userMapper.list(); } //@RequestMapping("/getOneUser") @GetMapping("/{id}") public User getOneUser(@PathVariable("id") int id) { return userMapper.selectByPrimaryKey(id); } //@RequestMapping("/addUser") @PostMapping("/") public int addUser(User user) { return userMapper.insert(user); } //@RequestMapping("/deleteUser") @DeleteMapping("/{id}") public int deleteUser(@PathVariable("id") int id) { return userMapper.deleteByPrimaryKey(id); } @PutMapping("/") public int updateUser(User user) { return userMapper.updateByPrimaryKey(user); }}
4.运行测试,浏览器 http://localhost:8090/user/1
<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>
2.创建配置类SwaggerConfig.java
.apis(RequestHandlerSelectors.basePackage("xyz.java1024.controller")) 对应controller所处的包
### 3.浏览器进入api页面 地址为:http://localhost:8090/swagger-ui.html### 4.调用get请求接口 ### 5.对于实体类型的请求参数体,我们在Controller接口加上@RequestBody 可读性会更加好!> 修改前> 修改后
//@RequestMapping("/addUser")@PostMapping("/")public int addUser(@RequestBody User user) { return userMapper.insert(user);}
> 重新启动刷新swagger-ui页面### 5.测试post请求> 把创建时间和更新时间参数去掉 ,填写用户名等参数,成功插入一条数据。### 6.swagger 增强> 对于实体的某些属性我们时不需要传的,并且我们不想它显示在swagger的请求体中,如 新增用户的 createdAt和updatedAt 等属性,我们可以通过在属性上面添加@ApiModelProperty(hidden = true)注解来隐藏属性
public class User implements Serializable {
private int id;
private String username;private String tel;private String password;private int status;@ApiModelProperty(hidden = true)private Timestamp createdAt;@ApiModelProperty(hidden = true)private Timestamp updatedAt;
> 此时重启刷新swagger页面,再次进入UserController的post可看到少了参数,如图参数变得相当简洁!
以上就是SpringBoot整合swagger实现测试Restful风格api的方法介绍,详细使用情况还得要大家自己使用过才能知道具体要领。如果想阅读更多相关内容的文章,欢迎关注亿速云行业资讯频道!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。