0


Java技术-接口文档-Swagger2&Swagger3&接口文档UI整合

Swagger 说明

Swagger是为了解决企业中接口(api)中定义统一标准规范的文档生成工具。方便各大后端小基友的懒问题,但是写注解也是妥妥的麻烦,但是如果版本迭代快或者人员的流动性大,会导致很多问题。所以很多企业中都会有统一的规范文档,来定义接口标准。

一、Swagger2完整用法

1.POM依赖

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

2.接口类

见【3.2】

3.实现类

见【3.3】

4.托管静态资源

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@EnableSwagger2
@EnableWebMvc
@Configuration
public class ApiDocConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

        super.addResourceHandlers(registry);

    }

}

5.接口文档配置

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;

@Configuration
public class SwaggerConf {
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()).enable(true)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.ikong.service.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("开放接口平台")
                .description("")
                .contact(new Contact("ikong", "http://ikong.ik.com", "[email protected]"))
                .version("1.0")
                .build();
    }
}

6.生产环境关闭接口文档

见【3.6】

7.Swagger3页面效果

Swagger2多包实现方法

二、Swagger3完整用法

1.POM依赖

2.接口类

3.实现类

4.托管静态资源

5.接口文档配置

6.生产环境关闭接口文档

7.Swagger3页面效果

三、Swagger整合Knife4jUi

1.POM依赖

<properties> <knife4j-swagger.version>3.0.3</knife4j-swagger.version> </properties>
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>${knife4j-swagger.version}</version>
</dependency>

2.接口类

import com.ikong.model.req.TestReq;
import com.ikong.model.ret.TestRet;
import com.jd.security.framework.common.model.Result;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

public interface TestApi {

    String test1(@RequestParam(value = "name") String name);

    TestRet test2(@RequestBody TestReq req);

    Result<TestRet> test3(@RequestBody TestReq req);
}

3.实现类


import com.ikong.api.TestApi;
import com.ikong.model.req.TestReq;
import com.ikong.model.ret.TestRet;
import com.jd.security.framework.common.model.Result;
import com.jd.security.framework.common.model.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

@Api(tags = "验证参数类型")
@RestController
@RequestMapping("/test")
public class TestApiController implements TestApi {

    @ApiOperation("001接收普通参数")
    @ApiImplicitParam(name = "name", value = "姓名", required = true)
    @GetMapping("test1")
    @Override
    public String test1(@RequestParam(value = "name") String name) {
        return "hello," + name;
    }

    @ApiOperation("002接收对象参数")
    @GetMapping("test2")
    @Override
    public TestRet test2(TestReq req) {
        return new TestRet(Long.valueOf(req.getId()), 200);
    }

    @ApiOperation("003返回标准格式")
    @PostMapping("test3")
    @Override
    public Result<TestRet> test3(@RequestBody TestReq req) {
        return ResultUtils.wrapSuccess(new TestRet(Long.valueOf(req.getId()), 200));
    }
}

4.托管静态资源


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class ApiDocHandlerConfiguration extends WebMvcConfigurationSupport {

    @Value("${swagger.enable:true}")
    private Boolean enable = false;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (enable) {
            registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }
}

5.接口文档配置


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2WebMvc
public class ApiDocKnife4jUiConfig {
    @Bean
    public Docket docket(Environment environment) {
        // 添加接口请求头参数配置 没有的话 可以忽略
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        tokenPar.name("token")
                .description("令牌")
                .defaultValue("")
                .modelRef(new ModelRef("string"))
                .parameterType("header").required(false).build();
        pars.add(tokenPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(true)//是否启动swagger 默认启动
                .groupName("ikong")//所在分组
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.ikong.service.impl"))//指定扫描的包路径
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(pars);
    }

    private ApiInfo apiInfo() {
        Contact author = new Contact("ikong", "api.ik.com", "[email protected]");
        return new ApiInfo(
                "开放平台接口文档",
                "开放平台接口文档",
                "1.0",
                "",
                author,
                "",
                "",
                new ArrayList<>()
        );

    }
}

6.生产环境关闭接口文档

application.properties

swagger.enable=false

7.Knife4jUi页面效果

URL : http://localhost:8083/doc.html

四、注释和参数讲解

参数说明:
name -- 参数名
value -- 参数说明
required -- 是否必须填写
dataType -- 数据类型
paramType -- 参数类型
example -- 举例
常用注解说明:

  • @Api()用于类;

表示标识这个类是swagger的资源

  • @ApiOperation()用于方法;

表示一个http请求的操作

  • @ApiParam()用于方法,参数,字段说明;

表示对参数的添加元数据(说明或是否必填等)

  • @ApiModel()用于类

表示对类进行说明,用于参数用实体类接收

  • @ApiModelProperty()用于方法,字段

表示对model属性的说明或者数据操作更改

  • @ApiIgnore()用于类,方法,方法参数

表示这个方法或者类被忽略

  • @ApiImplicitParam() 用于方法

表示单独的请求参数

  • @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam

具体使用说明:

1.@Api()

  ···
  @Api("测试用例1")
  @Controller
  public class swaggerTestUse(){
  }

2.@ApiOperation()

···
@Api("测试用例1")
@Controller
public class swaggerTestUse(){
    @ApiOperation(value = "apiOperationSwaggerTest", notes = "apiOperationSwagger测试")
    public void apiOperationSwaggerTest(){
    }
}

3.@ApiParam()

···
@Api("测试用例1")
@Controller
public class swaggerTestUse(){
    @ApiOperation(value = "apiOperationSwaggerTest", notes = "apiOperationSwagger测试")
    public void apiOperationSwaggerTest(@ApiParam(name = "id", value = "id入参", required = true) Integer id){
    }
}

4.@ApiModel()

···
@ApiModel(description = "测试实体类", value = "测试实体类")
public class Album implements Serializable {
    ···
}

5.@ApiModelProperty()

···
@ApiModel(description = "测试实体类", value = "测试实体类")
public class User implements Serializable {
    @ApiModelProperty(name = "userName", value = "用户名", required = false, exmaple = "小明")
    private String userName;
}

6.@ApiImplicitParams() 和@ApiImplicitParam()

    ···
  @Api("测试用例1")
  @Controller
  public class swaggerTestUse(){
      @ApiOperation(value = "apiOperationSwaggerTest", notes = "apiOperationSwagger测试")
      @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "id入参", required = true, dataType = "Integer", paramType = "query"),
                        @ApiImplicitParam(name = "brand", value = "brand", required = true, dataType = "BRAND", paramType = "body")
    })
      public void apiOperationSwaggerTest(Integer id, Brand band){
      }
  }

本文转载自: https://blog.csdn.net/philip502/article/details/131325658
版权归原作者 码者人生 所有, 如有侵权,请联系我们删除。

“Java技术-接口文档-Swagger2&Swagger3&接口文档UI整合”的评论:

还没有评论