SpringBoot来自Swagger的Restful文档生成

背景

  1. 基于SpringBoot的方案普遍要做到前后端分离
  2. 代码即文档
  3. 代码变化太快
  4. 文档经常忘记更改

方案

基于Swagger的方案可以比较简单的基于restful api做出相关文档

效果

点击try it out

可以看到结果如下

那么我们需要做什么呢?

代码

  1. 需要在pom里面引入swagger

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${swagger.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${swagger.version}</version>
    </dependency>
    <properties>
        <swagger.version>2.2.2</swagger.version>
    </properties>

     

  2.  新建swagger的配置类  
    package com.f6car.base.config;
     
    import com.f6car.base.constant.Constants;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
     
    /**
     * @author qixiaobo
     */
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
     
        @Bean
        public Docket createRestApi() {
            ApiInfo apiInfo = new ApiInfoBuilder()
                    .title("使用Swagger2构建RESTful APIs")
                    .description("客户端与服务端接口文档")
                    .termsOfServiceUrl("http://qixiaobo.site")
                    .contact("qixiaobo")
                    .version("1.0.0")
                    .build();
     
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage(Constants.CONTROLLER_PACKAGE))
                    .paths(PathSelectors.any())
                    .build();
        }
     
    }

    我们仅需要提供基础web包名即可

  3. 超类上增加简单注释【没有也没关系】

    /*
     * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
     * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
     * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
     * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
     * Vestibulum commodo. Ut rhoncus gravida arcu.
     */
     
    package com.f6car.base.controller.base;
     
    import com.f6car.base.common.*;
    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
     
    import java.io.Serializable;
    import java.util.List;
     
    /**
     * @author qixiaobo
     */
    public abstract class AbstractRestController<V extends Vo, S extends So> {
     
        @Autowired
        private Service<V, S> service;
     
     
        @PostMapping()
        @ApiOperation(value = "新建实体", notes = "")
        public Result add(@RequestBody V vo) {
            service.save(vo);
            return ResultGenerator.genSuccessResult();
        }
     
        @DeleteMapping("/{id}")
        @ApiOperation(value = "删除实体", notes = "")
        public Result delete(@PathVariable Serializable id) {
            service.deleteById(id);
            return ResultGenerator.genSuccessResult();
        }
     
     
        @PutMapping
        @ApiOperation(value = "更新实体", notes = "")
        public Result update(@RequestBody V vo) {
            service.update(vo);
            return ResultGenerator.genSuccessResult();
        }
     
        @GetMapping
        @ApiOperation(value = "获取实体列表", notes = "")
        public Result list(S so) {
            PageHelper.startPage(so.getCurrentPage(), so.getPageSize());
            List<V> list = service.findAll();
            PageInfo pageInfo = new PageInfo(list);
            return ResultGenerator.genSuccessResult(pageInfo);
        }
     
        @GetMapping("/{id}")
        @ApiOperation(value = "获取单个实体", notes = "")
        public Result detail(@PathVariable Serializable id) {
            V vo = service.findById(id);
            return ResultGenerator.genSuccessResult(vo);
        }
     
        @DeleteMapping("/batch")
        @ApiOperation(value = "批量删除实体", notes = "")
        public Result batchDelete(@RequestParam String ids) {
            service.deleteByIds(ids);
            return ResultGenerator.genSuccessResult();
        }
     
        @GetMapping("/batch")
        @ApiOperation(value = "批量获取实体", notes = "")
        public Result batchDetail(@RequestParam String ids) {
            List<V> vos = service.findByIds(ids);
            return ResultGenerator.genSuccessResult(vos);
        }
     
        @PostMapping("/batch")
        @ApiOperation(value = "批量新建实体", notes = "")
        public Result add(@RequestBody List<V> vos) {
            service.save(vos);
            return ResultGenerator.genSuccessResult();
        }
     
    }
  4. webConfig需要增加对html的处理【默认都是spring处理】

    @Configuration
    public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
     
     
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
             registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
     
             registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }

     

如上就可以简单的的生成

相关文章
相关标签/搜索