SpringBoot下使用Swagger2开发API文档

SpringBoot下使用Swagger2开发API文档

使用基础在前后端分离开发的后端代码简单案例上进行
下面是完整代码案例

1.依赖导入


        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            mysql
            mysql-connector-java
            5.1.47
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.0
        
        
        
            com.baomidou
            mybatis-plus-generator
            3.4.0
        
        
            org.apache.velocity
            velocity-engine-core
            2.2
        



        
        
            io.springfox
            springfox-swagger2
            2.9.2
        
        
            io.springfox
            springfox-swagger-ui
            2.9.2
        


        
         
        
            io.swagger
            swagger-annotations
            1.5.21
        
        
            io.swagger
            swagger-models
            1.5.21
        


        
            org.projectlombok
            lombok
            true
        

2.配置类

@Configuration
@EnableSwagger2 //开启注解

public class SwaggerConfig {
    //需要向Spring容器中注入一个Bean,会根据Swagger注解生成API文档
    @Bean
    public Docket buildDocket(){
        return new Docket(DocumentationType.SWAGGER_2)//使用的类型是SWAGGER_2类型
        .apiInfo(buildApiInfo())
        .select() //进行选择生成
//        .apis(RequestHandlerSelectors.any())//指定所有类都生成API com.example.stu.controller
        .apis(RequestHandlerSelectors.basePackage("com.example.stu.controller"))//指定哪些包下的类生成API
//        .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))//指定标记了特定注解的类进行生成
        .paths(PathSelectors.any())
                .build();
    }
    //设置文档的基本信息
    private ApiInfo buildApiInfo() {
        return new ApiInfoBuilder()
                .title("文档标题*******")
                .description("文档描述****")
                .version("版本****")
                .termsOfServiceUrl("服务支持网址")
                .license("许可协议")
                .licenseUrl("许可协议网址")
                .contact(new Contact("作者姓名","作者博客地址","email地址"))
                .build();
    }


}

3. application.properties

# 微服务命名
spring.application.name=stu-service
#端口声明
server.port=8089




#数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/temporary?useUnicode=true&useSSL=false&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=12345
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#logging.level.root=debug

4.实体类

@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value="Student对象", description="")
public class Student implements Serializable {

    private static final long serialVersionUID = 1L;
    @ApiModelProperty(name = "id",value = "编号",example = "1")
    @TableId(type = IdType.AUTO) //声明id 为自增长
    private Integer id;

    @ApiModelProperty(name = "name",value = "学生姓名",example = "张三",required = true)
    private String name;
    @ApiModelProperty(name = "sSex",value = "学生性别",example = "男",required = true)
    @TableField("s_sex")//用于字段匹配
    private String sSex;


}

5.返回前端数据封装类

//用于返回数据的封装
@Data
public class R {
    private Integer code;
    private Boolean status;
    private Map data =new HashMap<>();
    private String message;


    //私有构造方法
    private R(){}

    //链式编程
    public static R ok(){
        R r = new R();
        r.setStatus(true);
        r.setCode(200);
        return  r;
    }
    public static R error(String message,Integer code){
        R r =new R();
        r.setStatus(false);
        r.setCode(code);
        r.setMessage(message);
        return r;
    }

    //数据封装
    public R put(String key,Object value){
        this.data.put(key,value);
        return this;
    }


}

6.mapper及service

StudentMapper

public interface StudentMapper extends BaseMapper {

}

IStudentService

public interface IStudentService extends IService {

    Page pageList(StudentVo studentVo);
}

StudentServiceImpl

@Service
public class StudentServiceImpl extends ServiceImpl implements IStudentService {


    @Override
    public Page pageList(StudentVo studentVo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if(!StringUtils.isEmpty(studentVo.getName())){
            queryWrapper.eq("name",studentVo.getName());
        }
        if (!StringUtils.isEmpty(studentVo.getId())){
            queryWrapper.eq("id",studentVo.getId());
        }
        if (!StringUtils.isEmpty(studentVo.getSSex())){
            queryWrapper.eq("s_sex",studentVo.getSSex());
        }
        if (studentVo.getMaxId()!=null){
            queryWrapper.lt("id",studentVo.getMaxId());
        }
        if (studentVo.getMinId()!=null){
            queryWrapper.gt("id",studentVo.getMinId());
        }
        queryWrapper.orderByAsc("id");
        Page page = new Page();
        page.setCurrent(studentVo.getCurrentPage());
        page.setSize(studentVo.getPageSize());
        baseMapper.selectPage(page,queryWrapper);
        System.out.println(page.getTotal());

        return page;
    }
}

7. vo

StudentVo
主要用来与前端数据交互,涉及分页等信息

@Data
@ApiModel
public class StudentVo {
    @ApiModelProperty(name = "id",example = "1")
    private Integer id;
    private String name;
    private String sSex;
    @ApiModelProperty(name = "currentPage",value = "当前页",example = "1",required = true)
    private Integer currentPage;
    @ApiModelProperty(name = "pageSize",value = "每页显示条数",example = "3",required = true)
    private Integer pageSize;

    private Integer maxId;
    private  Integer minId;


}

8.controller

@Api(tags = "完成了student的CRUD功能")//tags对该类进行功能说明
@RestController
@RequestMapping("/stu/student")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    //RestFul风格
    //获取所有
    @ApiOperation("完成student列表的获取")//说明是一个操作项
    @GetMapping
    public R list(){
        return  R.ok().put("data",studentService.list());
    }

    @ApiOperation("完成student的分页查询")//说明是一个操作项

    //条件查询
    @PostMapping
    public R pageList(@ApiParam(name = "studentVo",value = "查询条件")@RequestBody StudentVo studentVo){
        Page pageList = studentService.pageList(studentVo);
        return R.ok().put("total",pageList.getTotal()).put("data",pageList.getRecords());

    }
    //新增
    @ApiOperation("完成student新增操作")
    @PostMapping("/save")
    public R save(@ApiParam(name = "student",value = "要新增的student")@RequestBody Student student){
        studentService.save(student);
        return R.ok();
    }
    //修改  先根据id获取结果返回给前端,前端在已有的基础上进行修改
    @ApiOperation("完成student修改前的查询")
    @GetMapping("/{id}")
    public R getById(@ApiParam(name = "id",value = "要修改对象的id",required = true)@PathVariable("id") Integer id){
        Student byId = studentService.getById(id);
        return R.ok().put("data",byId);
    }
//    提交后的修改操作
    @ApiOperation("完成student修改操作")
    @PutMapping()
    public R update(@ApiParam(name = "要修改的student",required = true)@RequestBody Student student){

        studentService.updateById(student);
        return R.ok();
    }

    //删除
    @ApiOperation("完成student的删除操作")
    @DeleteMapping("/{id}")
    public R deleteById(@ApiParam(name = "id",required = true,value = "要删除的学生id")@PathVariable("id") Integer id){
        studentService.removeById(id);
        return R.ok();
    }
    //删除
    @ApiOperation("完成student的批量删除操作")
    @DeleteMapping
    public R deleteByIds(@ApiParam("要删除的student id")@RequestParam List ids){
        studentService.removeByIds(ids);
        return R.ok();
    }


}

9.DemoApplication

@SpringBootApplication
@MapperScan("com.example.stu.mapper")
public class DemoApplication {


    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

10.最终显示结果

显示网址:http://localhost:8089/swagger-ui.html
SpringBoot下使用Swagger2开发API文档_第1张图片

SpringBoot下使用Swagger2开发API文档_第2张图片
SpringBoot下使用Swagger2开发API文档_第3张图片
SpringBoot下使用Swagger2开发API文档_第4张图片
SpringBoot下使用Swagger2开发API文档_第5张图片
SpringBoot下使用Swagger2开发API文档_第6张图片
SpringBoot下使用Swagger2开发API文档_第7张图片
SpringBoot下使用Swagger2开发API文档_第8张图片
SpringBoot下使用Swagger2开发API文档_第9张图片

你可能感兴趣的:(#,框架,SpringBoot)