Swagger简介
swagger包括三部分: Swagger Editor(基于浏览器的编辑器),Swagger UI(可以让我们通过浏览器来查看并操作Rest API,Swagger Codegen。
Swagger接口相关注解说明
1.@Api:可设置对控制器的描述
2. @ApiOperation:: 可设置对接口的描述
3 .@ApiIgnore: Swagger 文档不会显示拥有该注解的接口。
4 @ApiImplicitParams: 用于描述接口的非对象参数集。
5 @ApiImplicitParam: 用于描述接口的非对象参数,一般与 @ApiImplicitParams 组合使用。
6 @ApiModel:可设置接口相关实体的描述
7 @ApiModelProperty: 可设置实体属性的相关描述。
Swagger与SpringBoot实践
1 构建maven项目:可以从spring官网的Spring initializer页面生成一个空的springBoot 项目,然后添加如下依赖:
io.springfox springfox-swagger2 2.5.0 io.springfox springfox-swagger-ui 2.5.0
2 在项目中新建controller,model,configure包,然后再model里面创建User.class,UserController.class。
@Configuration @EnableSwagger2
//是否开启swagger,正式环境一般是需要关闭的(避免不必要的漏洞暴露!),可根据springboot的多环境配置进行设置 @ConditionalOnProperty(name = "swagger.enable", havingValue = "true") public class SwaggerApp {
@Value("${spring.application.name}") private String appName; @Value("${swagger.description}") private String nameDesc; @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .groupName("governance") .apiInfo(apiInfo()) .select() //为当前包路径 basePackage不能使用*,com.xxx.data.*.controller不对,可以少一层扩大扫描范围com.xxx.data .apis(RequestHandlerSelectors.basePackage("com.xxx.data.xxx.controller")) .paths(PathSelectors.any()) .build(); } @Bean public Docket createSystemParamRestApi() { return new Docket(DocumentationType.SWAGGER_2) .groupName("systemparam")//分组 .apiInfo(apiInfo()) .select() //为当前包路径 .apis(RequestHandlerSelectors.basePackage("com.xxx.data.xxx.controller")) .paths(PathSelectors.any()) .build(); } //构建 api文档的详细信息函数,注意这里的注解引用的是哪个 private ApiInfo apiInfo() { return new ApiInfoBuilder() //页面标题 .title(appName) //版本号 .version("1.0") //描述 .description(nameDesc+"API 描述") .build(); } }
修改添加application.properties文件
#是否激活 swagger true or false
swagger.enable=true
package cn.xdf.springboot.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.xdf.springboot.mapper.CategoryMapper; import cn.xdf.springboot.pojo.Category; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; /** * 控制层 简单演示增删改查及分页 * */ @RestController @RequestMapping("api") @Api("swaggerDemoController相关的api") public class SwaggerDemoController {
@Autowired CategoryMapper categoryMapper; private static final Logger logger= LoggerFactory.getLogger(SwaggerDemoController.class); //1.商品添加 //@PutMapping("add") 添加方法--restful风格 @PutMapping("add") @ApiOperation(value="商品新增") //正常业务时, 需要在category类里或者server层进行事务控制,控制层一般不进行业务控制的。 //@Transactional(rollbackFor = Exception.class) //@RequestParam 接收页面中的请求的参数 public Map addCategory(@RequestParam String name){ Category category = new Category(); category.setName(name); categoryMapper.save(category); logger.info("开始新增某个商品信息"); Map result = new HashMap(); result.put("respCode", "01"); result.put("respMsg", "新增成功!"); result.put("data", category); return result; } //2.商品修改 //@PostMapping("update") 修改方法--restful风格 @PostMapping("update") @ApiOperation(value = "商品修改", notes = "修改数据库中某个的商品信息") //@RequestBody 接收页面中的请求的参数对象(适用于post请求) //当入参为实体对象时,需要在方法上加@Valid或@Validated或者在参数前加@Valid或@Validated,或者在类上加@Validated public Map updateCategory(@Valid @RequestBody Category category) { Map result = new HashMap(); Category categoryGet = categoryMapper.get(category.getId()); if(categoryGet == null || "".equals(categoryGet)){ try { throw new Exception("修改的该商品不存在!"); } catch (Exception e) { e.printStackTrace(); } result.put("respCode", "03"); result.put("respMsg", "修改的该商品不存在!"); result.put("data", category); return result; } categoryMapper.update(category); logger.info("开始修改某个商品信息"); result.put("respCode", "03"); result.put("respMsg", "修改成功!"); result.put("data", category); return result; } //3.商品删除 //@DeleteMapping("/delete/{id}") 删除方法--restful风格 @DeleteMapping("/delete/{id}") @ApiOperation(value = "根据id删除商品", notes = "商品删除") @ApiImplicitParam(name = "id", value = "商品ID", paramType = "path", required = true, dataType = "Integer") public Map deleteCategory(@PathVariable int id)throws Exception{ //@PathVariable 获取/delete/{id}中id Category category = categoryMapper.get(id); Map result = new HashMap(); if (category == null) { try { throw new Exception("用户ID:" + id + ",未找到"); } catch (Exception e) { e.printStackTrace(); } result.put("respCode", "02"); result.put("respMsg", "数据库无该商品信息,删除失败!"); result.put("data", category); return result; }else{ categoryMapper.delete(id); logger.info("开始删除某个商品信息"); result.put("respCode", "01"); result.put("respMsg", "删除成功!"); result.put("data", category); return result; } } //4.根据ID查询商品信息 //@GetMapping("") 查询方法--restful风格 @GetMapping("/get/{id}") @ApiOperation(value = "根据id查询商品", notes = "查询数据库中某个的商品信息") @ApiImplicitParam(name = "id", value = "商品ID", paramType = "path", required = true, dataType = "Integer") public Map getCategory(@PathVariable int id) { //@PathVariable 获取/get/{id}中id Category category = categoryMapper.get(id); logger.info("开始查询某个商品信息"); Map result = new HashMap(); if (category == null) { try { throw new Exception("用户ID:" + id + ",未找到"); } catch (Exception e) { e.printStackTrace(); } result.put("respCode", "02"); result.put("respMsg", "数据库无该商品信息"); result.put("data", category); return result; }else{ result.put("respCode", "01"); result.put("respMsg", "查询成功!"); result.put("data", category); return result; } } //5.分页查询 //@GetMapping("") 查询方法--restful风格 @GetMapping("/page") @ApiOperation(value="商品查询(分页)") public Map pageCategory(@RequestParam(value="start",defaultValue="0")int start,@RequestParam(value = "size", defaultValue = "5") int size) throws Exception { //1. 在参数里接受当前是第几页 start ,以及每页显示多少条数据 size。 默认值分别是0和5。 //2. 根据start,size进行分页,并且设置id 倒排序 PageHelper.startPage(start,size,"id desc"); //3. 因为PageHelper的作用,这里就会返回当前分页的集合了 List cs = categoryMapper.findAll(); logger.info("开始分页查询商品信息"); //4. 根据返回的集合,创建PageInfo对象 PageInfo page = new PageInfo(cs); Map result = new HashMap(); result.put("respCode", "01"); result.put("respMsg", "成功"); result.put("data", page); return result; } }
这样swagger2与springboot就集成完毕了。
看下最终效果吧:
访问路径: http://localhost:8080/swagger-ui.html
调试:点击需要访问的api列表,点击try it out!按钮,表示 执行。