SpringBoot Swagger增强版【knife4j】基础使用

812 阅读2分钟

SpringBoot Swagger增强版【knife4j】基础使用方式.

1.在项目pom.xml中导入依赖

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.2</version>
</dependency>

2.在WebMvcConfig上,添加相应配置:注释和返回配置类.

@Slf4j
@Configuration
@EnableSwagger2 //使用swagger
@EnableKnife4j  //使用swagger增强
public class WebMvcConfig implements WebMvcConfigurer {

    //开始进行静态资源映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** 设置访问后台页面的路径
         * 下方这个配置的意思是,将 /backend/** 的请求映射到 resources文件下:/backend/
         * 重点:【classpath】就是resources
         * */
         // 注册swagger生成的相关文档路径
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * Knife4j的配置基
     */
    @Bean
    public Docket createRestApi() {
        //指定接口扫描的包
        Predicate<RequestHandler> requestHandlerPredicate = RequestHandlerSelectors.basePackage("com.example.rejiwaimai2.main.*.controller");
        //返回文档类型
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(this.apiInfo())
                .select()
                .apis(requestHandlerPredicate)
                .paths(PathSelectors.any())
                .build();
    }
    /**
    * 接口文档的描述
    */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("吉吉跑腿")
                .version("1.0")
                .description("吉吉跑腿接口文档").build();
    }
}

3.(非必需)根据具体项目情况,在登录拦截器(或过滤器)中加入【不进行权限验证】路径列表.

路径地址:1."/swagger-resources";2."/v2/api-docs";

4.swagger常用注解的基本使用.

@Api --> 用在请求的类上,使用Controller,表示对类的说明;

@ApiModel --> 用在Dto/Vo/Entity等数据类上,对该类用途进行说明;

@ApiModelProperty --> 用在Dto/Vo/Entity等数据类中的属性上,对该类的每一项属性进行说明.

@ApiOperation --> 用在请求的方法上,描述请求的作用.

@ApilmplicitParams --> 用在请求的方法上,对请求方法的一组入参进行描述.

@ApilmplicitParam --> 用在@ApilmplicitParams注解中,指定这一组入参中单个入参的类型和作用.

使用示例:


@Api

image.png

效果对比:

image.png

image.png


@ApiOperation

image.png 效果对比:

image.png image.png


@ApilmplicitParams与ApilmplicitParam是一套组合API,必然是一起使用的. image.png 效果对比:

image.png

image.png


@ApiModel和@ApiModelProperty两个也是一套组合API,必须是一起使用的.

image.png

效果对比:

image.png

image.png

完.