使用knife4j生成自动接口文档

一、简介

knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案。

二、实现步骤

1、导入knife4j的maven坐标

<!--        springboot集成swagger-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>

2、导入knife4j相关配置类

在WebMvcConfig类中加入注解启用swagger,以及配置接口文档的相关信息

注解:
WebMvcConfig类上加注解:@EnableSwagger2和@EnableKnife4j
 @Bean
    public Docket createRestApi() {
        // 文档类型
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.weisi.smartTest.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().contact(new Contact("张三","http://wwww.baidu.com","test@qq.com"))
                .title("smart_test")
                .version("1.0")
                .description("smart_test接口文档")
                .build();
    }


3、设置静态资源,否则接口文档页面无法访问

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

4、在LoginCheckFilter中设置不需要处理的请求路径

//定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

5.访问:http://localhost:8080/doc.html

三、优化使用

默认生成的接口文档不够人性化,可以将我们平时在注释里面写的内容放到对应的注解里面,这样生成的文档就会有我们定制的信息。

注解
说明
@Api:用在请求的类上,例如Controller,表示对类的说明
@ApiModel:用在类上,通常是实体类,表示一个返回响应数据的信息
@ApiModelProperty:用在属性上,描述响应类的属性
@ApiOperation:用在请求的方法上,说明方法的用途、作用
@ApilmplicitParams:用在请求的方法上,表示一组参数说明
@ApilmplicitParam:用在@ApilmplicitParams注解中,指定一个请求参数的各个方面





posted @ 2024-04-18 16:22  测试微思录-静水流深  阅读(92)  评论(0)    收藏  举报