springboot项目集成swagger

前言

本文档为转发记录!
原文链接:http://www.importnew.com/29514.html

Swagger2介绍
Swagger是一款RESTful接口的文档在线自动生成、功能测试功能框架。一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务,加上swagger-ui,可以有很好的呈现。 让手机端 前端可以很方便的知道返回数据


image.png

SpringBoot集成
这里选用的swagger版本为:2.8.0
1.pom依赖



    io.springfox
    springfox-swagger2
    2.8.0


    io.springfox
    springfox-swagger-ui
    2.8.0

2.编写配置文件(Swagger2Config.java)
主要是添加注解@EnableSwagger2和定义Docket的bean类。

@EnableSwagger2
@Configuration
public class SwaggerConfig {
 
    //是否开启swagger,正式环境一般是需要关闭的,可根据springboot的多环境配置进行设置
    @Value(value = "${swagger.enabled}")
    Boolean swaggerEnabled;
 
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                // 是否开启
                .enable(swaggerEnabled).select()
                // 扫描的路径包
                .apis(RequestHandlerSelectors.basePackage("cn.lqdev.learning.springboot.chapter10"))
                // 指定路径处理PathSelectors.any()代表所有的路径
                .paths(PathSelectors.any()).build().pathMapping("/");
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot-Swagger2集成和使用-demo示例")
                .description("oKong | 趔趄的猿")
                // 作者信息
                .contact(new Contact("oKong", "https://blog.lqdev.cn/", "[email protected]"))
                .version("1.0.0")
                .build();
    }
}

3.添加文档内容(一般上是在Controller,请求参数上进行注解,这里以上章节的

/**
 * 用户控制层 简单演示增删改查及分页
 * 新增了swagger文档内容 2018-07-21
 * @author oKong
 *
 */
@RestController
@RequestMapping("/user")
@Api(tags="用户API")
public class UserController {
 
    @Autowired
    IUserService userService;
 
    @PostMapping("add")
    @ApiOperation(value="用户新增")
    //正常业务时, 需要在user类里面进行事务控制,控制层一般不进行业务控制的。
    //@Transactional(rollbackFor = Exception.class)
    public Map addUser(@Valid @RequestBody UserReq userReq){
 
        User user = new User();
        user.setCode(userReq.getCode());
        user.setName(userReq.getName());
        //由于设置了主键策略 id可不用赋值 会自动生成
        //user.setId(0L);
        userService.insert(user);
        Map result = new HashMap();
        result.put("respCode", "01");
        result.put("respMsg", "新增成功");
        //事务测试
        //System.out.println(1/0);
        return result;
    }
 
    @PostMapping("update")
    @ApiOperation(value="用户修改")    
    public Map updateUser(@Valid @RequestBody UserReq userReq){
 
        if(userReq.getId() == null || "".equals(userReq.getId())) {
            throw new CommonException("0000", "更新时ID不能为空");
        }
        User user = new User();
        user.setCode(userReq.getCode());
        user.setName(userReq.getName());
        user.setId(Long.parseLong(userReq.getId()));        
        userService.updateById(user);
        Map result = new HashMap();
        result.put("respCode", "01");
        result.put("respMsg", "更新成功");
        return result;
    }
 
    @GetMapping("/get/{id}")
    @ApiOperation(value="用户查询(ID)")    
    @ApiImplicitParam(name="id",value="查询ID",required=true)
    public Map getUser(@PathVariable("id") String id){
        //查询
        User user = userService.selectById(id);
        if(user == null) {
            throw new CommonException("0001", "用户ID:" + id + ",未找到");
        }
        UserResp resp = UserResp.builder()
                .id(user.getId().toString())
                .code(user.getCode())
                .name(user.getName())
                .status(user.getStatus())
                .build();
        Map result = new HashMap();
        result.put("respCode", "01");
        result.put("respMsg", "成功");
        result.put("data", resp);
        return result;
    }
 
    @GetMapping("/page")
    @ApiOperation(value="用户查询(分页)")        
    public Map pageUser(int current, int size){
        //分页
        Page page = new Page<>(current, size);
        Map result = new HashMap();
        result.put("respCode", "01");
        result.put("respMsg", "成功");
        result.put("data", userService.selectPage(page));
        return result;
    }
 
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
//加入@ApiModel
@ApiModel
public class UserReq {
 
    @ApiModelProperty(value="ID",dataType="String",name="ID",example="1020332806740959233")
    String id;
 
    @ApiModelProperty(value="编码",dataType="String",name="code",example="001")
    @NotBlank(message = "编码不能为空")
    String code;
 
    @ApiModelProperty(value="名称",dataType="String",name="name",example="oKong")
    @NotBlank(message = "名称不能为空")
    String name;
}

Swagger访问与使用
api首页路径:http://127.0.0.1:8080/swagger-ui.html
调试:点击需要访问的api列表,点击try it out!按钮,即可弹出一下页面:

image.png

4.swagger常见属性
image.png

你可能感兴趣的:(springboot项目集成swagger)