springboot(9) 整合Swagger-UI

Swagger-UI可以生成动态的API文档,方便调试测试

注意:Swagger对生成API文档的范围有三种不同的选择

  • 生成指定包下面的类的API文档
  • 生成有指定注解的类的API文档
  • 生成有指定注解的方法的API文档

当生成指定包下面的类的API文档时,controller中没有加注释的请求接口也会生成API

一. springboot中使用swagger

1.pom.xml


    <dependency>
      <groupId>io.springfoxgroupId>
      <artifactId>springfox-swagger2artifactId>
      <version>2.7.0version>
    dependency>
    <dependency>
      <groupId>io.springfoxgroupId>
      <artifactId>springfox-swagger-uiartifactId>
      <version>2.7.0version>
    dependency>

2.增加swagger文档API配置类

/**
 * Swagger2API文档的配置
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包下controller生成API文档
                .apis(RequestHandlerSelectors.basePackage("com.yy.mallTiny.controller"))
                //为有@Api注解的Controller生成API文档
//                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                //为有@ApiOperation注解的方法生成API文档
//                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SwaggerUI演示")
                .description("mall-tiny")
                //.contact("macro")
                .version("1.0")
                .build();
    }
}

3.增加标签注释

@Api @ApiOperation @ApiModelProperty
@Api(tags = "PmsBrandController", value = "商品品牌管理")
@Controller
@RequestMapping("/brand")
public class PmsBrandController {
    @Autowired
    PmsBrandService brandService;

    @ApiOperation("分页查询品牌列表")
    @RequestMapping(value = "page", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult> getPageBrand(int pageNum, int pageSize){
        PageInfo pageInfo = brandService.listBrand(pageNum, pageSize);
        return CommonResult.success(CommonPage.restPage(pageInfo), "success");
    }
// 没有swagger注释也会生成API
  @RequestMapping(value = "list", method = RequestMethod.GET)
  @ResponseBody
  public CommonResult> list(int pageNum, int pageSize){
  PageInfo pageInfo = brandService.listBrand(pageNum, pageSize);
  return CommonResult.success(CommonPage.restPage(pageInfo), "success");
  }
}
public class PmsBrand {
    private Long id;

    private String name;

    @ApiModelProperty(value = "首字母")
    private String firstLetter;

    private Integer sort;

    @ApiModelProperty(value = "是否为品牌制造商:0->不是;1->是")
    private Integer factoryStatus;

    private Integer showStatus;

    @ApiModelProperty(value = "产品数量")
    private Integer productCount;

运行项目, 访问http://localhost:8080/swagger-ui.html

 

 

 可以直接发请求,测试接口,

springboot(9) 整合Swagger-UI_第1张图片

 

 

 还可以看到对返回参数的注释

springboot(9) 整合Swagger-UI_第2张图片

 

 

 二。mybatis生成带@ApiModelProperty注释的model

1.自定义注释生成器

/**
 * 自定义注释生成器
 * Created by macro on 2018/4/26.
 */
public class CommentGenerator extends DefaultCommentGenerator {
    private boolean addRemarkComments = false;
    private static final String EXAMPLE_SUFFIX="Example";
    private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty";

    /**
     * 设置用户配置的参数
     */
    @Override
    public void addConfigurationProperties(Properties properties) {
        super.addConfigurationProperties(properties);
        this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
    }

    /**
     * 给字段添加注释
     */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
                                IntrospectedColumn introspectedColumn) {
        String remarks = introspectedColumn.getRemarks();
        //根据参数和备注信息判断是否添加备注信息
        if(addRemarkComments&&StringUtility.stringHasValue(remarks)){
//            addFieldJavaDoc(field, remarks);
            //数据库中特殊字符需要转义
            if(remarks.contains("\"")){
                remarks = remarks.replace("\"","'");
            }
            //给model的字段添加swagger注解
            field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")");
        }
    }

    /**
     * 给model的字段添加注释
     */
    private void addFieldJavaDoc(Field field, String remarks) {
        //文档注释开始
        field.addJavaDocLine("/**");
        //获取数据库字段的备注信息
        String[] remarkLines = remarks.split(System.getProperty("line.separator"));
        for(String remarkLine:remarkLines){
            field.addJavaDocLine(" * "+remarkLine);
        }
        addJavadocTag(field, false);
        field.addJavaDocLine(" */");
    }

    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {
        super.addJavaFileComment(compilationUnit);
        //只在model中添加swagger注解类的导入
        if(!compilationUnit.isJavaInterface()&&!compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)){
            compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
        }
    }
}

2.mybatis-generator.xml中增加生成注释

<context id="DB2Tables"    targetRuntime="MyBatis3">
        
        
        
        
            
            
            
            
        

3.生成mybatis generator的类

使用 mvn mybatis-generator:generate 直接生成会报错,

[ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate (default-cli) on project mall-tiny: Execution default-cli of goa
l org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate failed: Cannot instantiate object of type com.yy.mallTiny.mybatisGenerator.CommentGenerator

所以使用代码来生成

/**
 * 用于生产MBG的代码
 * Created by macro on 2018/4/26.
 */
public class Generator {
    public static void main(String[] args) throws Exception {
        //MBG 执行过程中的警告信息
        List warnings = new ArrayList();
        //当生成的代码重复时,覆盖原代码
        boolean overwrite = true;
        //读取我们的 MBG 配置文件
        InputStream is = Generator.class.getResourceAsStream("/mybatis-generator.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        is.close();

        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        //创建 MBG
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        //执行生成代码
        myBatisGenerator.generate(null);
        //输出警告信息
        for (String warning : warnings) {
            System.out.println(warning);
        }
    }
}

执行main方法就能看到生成的model中有注释了

springboot(9) 整合Swagger-UI_第3张图片

 

你可能感兴趣的:(springboot(9) 整合Swagger-UI)