SpringBoot +Swagger2整合使用示范
- 添加依赖:
<!-- 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>
- 添加配置
@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
@Bean
public Docket createRestApi()
{
return new Docket(DocumentationType.SWAGGER_2).apiInfo(getApiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.humorchen.springboot_test.controller")).paths(PathSelectors.any()).build();
}
private ApiInfo getApiInfo()
{
return new ApiInfoBuilder().title("SprintBoot学习测试接口文档").description("描述信息:author:humorchen").contact("联系信息:qq3301633914").version("1.0").build();
}
}
- 使用注解开发
- 实体类
@Component
@TableName("`User`")
@ApiModel("用户实体类")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "用户唯一标识",required = false,hidden = true)
@TableId(value="id", type= IdType.AUTO)
private Integer id;
@ApiModelProperty("用户名")
private String username;
@ApiModelProperty("用户密码")
private String password;
//getter setter...
}
/**
* <p>
* 前端控制器
* </p>
*
* @author humorchen
* @since 2020-11-05
*/
@RestController
@RequestMapping("/springboot_test/user")
@Api(value = "用户接口")
public class UserController {
@Autowired
private IUserService iUserService;
private final static Logger logger = LoggerFactory.getLogger(UserController.class);
@GetMapping(value = "/{id}")
@ApiOperation("根据用户唯一标识获取用户信息")
public R getUser(@PathVariable @NonNull @ApiParam("用户唯一标识") String id)
{
return new R(iUserService.selectById(id));
}
@GetMapping(value = "/")
@ApiOperation("获取所有用户")
public R getAllUser(){
return new R(iUserService.selectList(null));
}
@PostMapping(value = "/")
@ApiOperation("添加用户")
public R addUser(@RequestBody @ApiParam("用户信息") User user){
if(iUserService.insert(user)){
return new R().success("注册成功",user);
}
return new R().error("注册失败");
}
@PutMapping(value = "/{id}")
@ApiOperation("修改用户信息")
public Object updateUser(@PathVariable @ApiParam(value = "用户唯一标识符") String id,@RequestBody @ApiParam(value = "用户信息") User new_user){
User existed=iUserService.selectById(id);
if(existed==null){
return new R().error("用户不存在");
}
new_user.setId(existed.getId());
//权限检查
if(iUserService.updateById(new_user)){
return new R().success("用户信息更新成功",new_user);
}
return new R().error("用户信息修改失败");
}
}
- 查看Swagger接口
本文来自博客园,作者:HumorChen99,转载请注明原文链接:https://www.cnblogs.com/HumorChen/p/18039700