springboot集成swagger,生成接口api

需要的依赖配置

  
      io.springfox
      springfox-swagger-ui
      2.8.0
  
  
      io.springfox
      springfox-swagger2
      2.8.0
  

在配置文件中添加

swagger:
  host: 9990

然后在控制类的包结构下面添加一个配置类:

package com.chuxin.fight.demo.controller;

import org.springframework.beans.factory.annotation.Value;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @FileName: Swagger
 * @Description: swagger2
 */
@Configuration
@EnableSwagger2
public class Swagger2 {

    @Value("${swagger.host}")
    private String swaggerHost;


    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包路径
                .apis(RequestHandlerSelectors.basePackage("com.chuxin.fight.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("自学 swagger 接口文档")
                //创建人
                .contact(new Contact("###", "#", ""))
                //版本号
                .version("1.0")
                //描述
                .description("文档描述")
                .build();
    }
}

在每个控制类里面添加注解

@RequestMapping(value = "/test", produces = "application/json; charset=utf-8")
@Api(value = "test接口", description = "test接口", tags = {"test接口"})

在方法上面添加两个参数

@ApiOperation(value = "import", notes = "import")//接口描述
@ApiImplicitParams({//接口入参
            @ApiImplicitParam(name = "keyWord", value = "搜索使用的关键字", paramType = "query", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query", required = true, dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", paramType = "query", required = true, dataType = "int", defaultValue = "5"),
    })

然后启动项目:
访问(http://127.0.0.1:8080/api/swagger-ui.html)【ip:port/项目路径/swagger-ui.html】即可!


2020-10-10补充
上面说的一种形式打开之后是一种文档格式,最近又发现一种新的文档格式,前面配置都一样,只需要多添加一个依赖就可以了

       
            com.github.xiaoymin
            knife4j-spring-boot-starter
            2.0.4
        

然后启动项目,访问(http://127.0.0.1:8080/api/doc.html)【ip:port/项目路径/doc.html】即可!
见下图:

image.png

你可能感兴趣的:(springboot集成swagger,生成接口api)