Swagger2和Knife4j

Swagger


1、添加依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.2.2</version>
</dependency>
复制代码

2、编写配置类

2.1、单个分组

@Configuration
@EnableSwagger2
@Profile({"dev", "test"}) // 只在dev和test环境生效
public class SwaggerConfiguration {

    @Bean
    public Docket defaultApi1() {
        return new Docket(DocumentationType.SWAGGER_2).
                apiInfo(apiIanfo()).
                groupName("1.0版本").
                select().
                apis(RequestHandlerSelectors.basePackage("com.zhf.stujpa.controller")).
                paths(PathSelectors.any()).
                build();
    }

    public ApiInfo apiIanfo(){
       return new ApiInfoBuilder().
                title("我的测试接口").
                description("我的测试接口").
                contact(new Contact("张海峰","http://XX.com","[email protected]")).
                build();
    }

}
复制代码

2.2、多个分组

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket defaultApi1() {
        return new Docket(DocumentationType.SWAGGER_2).
                apiInfo(apiIanfo()).
                groupName("用户控制器").
                select().
                apis(RequestHandlerSelectors.basePackage("com.zhf.stu.controller.user")).
                /**
                	通过路径来分组
                	PathSelectors.ant("/api/station/operation/**")
                */
            	paths(PathSelectors.any()).
                build();
    }

    public ApiInfo apiIanfo(){
       return new ApiInfoBuilder().
                title("我的测试接口").
                description("我的测试接口").
                contact(new Contact("张海峰","http://XX.com","[email protected]")).
                build();
    }
     @Bean
    public Docket defaultApi1() {
        return new Docket(DocumentationType.SWAGGER_2).
                apiInfo(apiIanfo()).
                groupName("角色控制器").
                select().
                apis(RequestHandlerSelectors.basePackage("com.zhf.stu.controller.role")).
                paths(PathSelectors.any()).
                build();
    }

}
复制代码

Knife4j


1、添加依赖

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>2.0.7</version>
</dependency>
复制代码

2、编写配置类

2.1、单个分组

@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {

    @Bean(value = "defaultApi1")
    public Docket defaultApi1() {
        Docket docket=new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //分组名称
                .groupName("2.X版本")
                .select()
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.zhf.stu.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }
  
  public ApiInfo apiIanfo(){
       return new ApiInfoBuilder().
                title("我的测试接口").
                description("我的测试接口").
                contact(new Contact("张海峰","http://XX.com","[email protected]")).
                build();
    }
}
复制代码

2.2、多个分组

  • 创建配置属性类/
@Data
@ConfigurationProperties(prefix = "stu.swagger")
public class SwaggerProperties {
    private String title = "在线文档"; //标题
    private String group = ""; //自定义组名
    private String description = "在线文档"; //描述
    private String version = "1.0"; //版本
    private Contact contact = new Contact(); //联系人
    private String basePackage = "com.zhf.stu"; //swagger会解析的包路径
    private List<String> basePath = new ArrayList<>(); //swagger会解析的url规则
    private List<String> excludePath = new ArrayList<>();//在basePath基础上需要排除的url规则
    private Map<String, DocketInfo> docket = new LinkedHashMap<>(); //分组文档
	public String getGroup() {
        if (group == null || "".equals(group)) {
            return title;
        }
        return group;
    }
    @Data
    public static class DocketInfo {
        private String title = "在线文档"; //标题
        private String group = ""; //自定义组名
        private String description = "在线文档"; //描述
        private String version = "1.0"; //版本
        private Contact contact = new Contact(); //联系人
        private String basePackage = ""; //swagger会解析的包路径
        private List<String> basePath = new ArrayList<>(); //swagger会解析的url规则
        private List<String> excludePath = new ArrayList<>();//在basePath基础上需要排除的url
        public String getGroup() {
            if (group == null || "".equals(group)) {
                return title;
            }
            return group;
        }
    }
    @Data
    public static class Contact {
        private String name = "pinda"; //联系人
        private String url = ""; //联系人url
        private String email = ""; //联系人email
    }
}
复制代码
  • 创建application.yml文件
server:
  port: 10086
stu:
  swagger:
    enabled: true #是否启用swagger
    docket:
      user:
        title: 用户模块
        base-package: com.zhf.stu.controller.user
      menu:
        title: 角色模块
        base-package: com.zhf.stu.controller.role
复制代码
  • 创建配置类SwaggerAutoConfiguration
@Configuration
@ConditionalOnProperty(name = "pinda.swagger.enabled", havingValue = "true", 
                       matchIfMissing = true)
@EnableSwagger2
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfiguration implements BeanFactoryAware {
    @Autowired
    SwaggerProperties swaggerProperties;
  
    private BeanFactory beanFactory;
    @Bean
    @ConditionalOnMissingBean
    public List<Docket> createRestApi(){
        ConfigurableBeanFactory configurableBeanFactory = 
            								(ConfigurableBeanFactory) beanFactory;
        List<Docket> docketList = new LinkedList<>();
        // 没有分组
        if (swaggerProperties.getDocket().isEmpty()) {
            Docket docket = createDocket(swaggerProperties);
            configurableBeanFactory.registerSingleton(swaggerProperties.getTitle(), 
                                                      docket);
            docketList.add(docket);
            return docketList;
        }
        // 分组创建
        for (String groupName : swaggerProperties.getDocket().keySet()){
            SwaggerProperties.DocketInfo docketInfo = 
                swaggerProperties.getDocket().get(groupName);
            ApiInfo apiInfo = new ApiInfoBuilder()
                    //页面标题
                    .title(docketInfo.getTitle())
                    //创建人
                    .contact(new Contact(docketInfo.getContact().getName(),
                            docketInfo.getContact().getUrl(),
                            docketInfo.getContact().getEmail()))
                    //版本号
                    .version(docketInfo.getVersion())
                    //描述
                    .description(docketInfo.getDescription())
                    .build();

            // base-path处理
            // 当没有配置任何path的时候,解析/**
            if (docketInfo.getBasePath().isEmpty()) {
                docketInfo.getBasePath().add("/**");
            }
            List<Predicate<String>> basePath = new ArrayList<>();
            for (String path : docketInfo.getBasePath()) {
                basePath.add(PathSelectors.ant(path));
            }

            // exclude-path处理
            List<Predicate<String>> excludePath = new ArrayList<>();
            for (String path : docketInfo.getExcludePath()) {
                excludePath.add(PathSelectors.ant(path));
            }

            Docket docket = new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo)
                	.groupName(docketInfo.getGroup())
                    .select()
                    //为当前包路径
                    .apis(RequestHandlerSelectors.basePackage(docketInfo.getBasePackage()))
                    .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)),Predicates.or(basePath)))
                    .build();
            configurableBeanFactory.registerSingleton(groupName, docket);
            docketList.add(docket);
        }
        return docketList;
    }

    //构建 api文档的详细信息
    private ApiInfo apiInfo(SwaggerProperties swaggerProperties) {
        return new ApiInfoBuilder()
                //页面标题
                .title(swaggerProperties.getTitle())
                //创建人
                .contact(new Contact(swaggerProperties.getContact().getName(),
                                        swaggerProperties.getContact().getUrl(),
                                        swaggerProperties.getContact().getEmail()))
                //版本号
                .version(swaggerProperties.getVersion())
                //描述
                .description(swaggerProperties.getDescription())
                .build();
    }

    //创建接口文档对象
    private Docket createDocket(SwaggerProperties swaggerProperties) {
        //API 基础信息
        ApiInfo apiInfo = apiInfo(swaggerProperties);

        // base-path处理
        // 当没有配置任何path的时候,解析/**
        if (swaggerProperties.getBasePath().isEmpty()) {
            swaggerProperties.getBasePath().add("/**");
        }
        List<Predicate<String>> basePath = new ArrayList<>();
        for (String path : swaggerProperties.getBasePath()) {
            basePath.add(PathSelectors.ant(path));
        }

        // exclude-path处理
        List<Predicate<String>> excludePath = new ArrayList<>();
        for (String path : swaggerProperties.getExcludePath()) {
            excludePath.add(PathSelectors.ant(path));
        }

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .groupName(swaggerProperties.getGroup())
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)),Predicates.or(basePath)))
                .build();
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
复制代码

常用注解


@Api

用在类上,该注解将一个Controller(Class)标注为一个swagger资源(API)。

  • tags API分组标签。具有相同标签的API将会被归并在一组内展示。
  • value 如果tags没有定义,value将作为Api的tags使用

@ApiOperation

在指定的(路由)路径上,对一个操作或HTTP方法进行描述。具有相同路径的不同操作会被归组为同一个操作对象。

  • value 对操作的简单说明,长度为120个字母,60个汉字。
  • notes 对操作的详细说明。
  • httpMethod HTTP请求的动作名,可选值有:"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"。
  • code 默认为200,有效值必须符合标准的HTTP Status Code Definitions

@ApiImplicitParams

用在方法上,注解ApiImplicitParam的容器类,以数组方式存储。

@ApiImplicitParam

对API的单一参数进行注解。虽然注解@ApiParam同JAX-RS参数相绑定,但这个@ApiImplicitParam注解可以以统一的方式定义参数列表,也是在Servelet及非JAX-RS环境下,唯一的方式参数定义方式。

@ApiParam

增加对参数的元信息说明。这个注解只能被使用在JAX-RS 1.x/2.x的综合环境下。其主要的属性有

  • required 是否为必传参数,默认为false
  • value 参数简短说明

@ApiResponses

注解@ApiResponse的包装类,数组结构。即使需要使用一个@ApiResponse注解,也需要将@ApiResponse注解包含在注解@ApiResponses内。

@ApiResponse

描述一个操作可能的返回结果。当REST API请求发生时,这个注解可用于描述所有可能的成功与错误码。可以用,也可以不用这个注解去描述操作的返回类型,但成功操作的返回类型必须在@ApiOperation中定义。如果API具有不同的返回类型,那么需要分别定义返回值,并将返回类型进行关联。但Swagger不支持同一返回码,多种返回类型的注解。注意:这个注解必须被包含在@ApiResponses注解中。

  • code HTTP请求返回码。有效值必须符合标准的HTTP Status Code Definitions
  • message 更加易于理解的文本消息
  • response 返回类型信息,必须使用完全限定类名,比如“com.xyz.cc.Person.class”。
  • responseContainer 如果返回类型为容器类型,可以设置相应的值。有效值为 "List", "Set" or "Map",其他任何无效的值都会被忽略。

@ApiModel

描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)

  • value model的别名,默认为类名
  • description model的详细描述

@ApiModelProperty

描述一个model的属性

  • value 属性简短描述
  • example 属性的示例值
  • required 是否为必须值

若有收获,就点个赞吧

猜你喜欢

转载自juejin.im/post/7079612432116613151