springboot集成Swagger-knife4j(三)

在springboot集成Swagger-knife4j接口文档

本文章内容很多来自狂神说视频学习
狂神说Swagger学习推荐视频: https://www.bilibili.com/video/BV1PE411i7CV?p=48.

pom.xml配置依赖

    <dependencies>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.49version>
        dependency>
        <dependency>
            <groupId>io.swaggergroupId>
            <artifactId>swagger-annotationsartifactId>
            <version>1.5.22version>
            <scope>compilescope>
        dependency>
        <dependency>
            <groupId>com.github.xiaoymingroupId>
            <artifactId>knife4j-spring-boot-starterartifactId>
            <version>2.0.4version>
        dependency>
    dependencies>

SwaggerConfig

package com.zm.web.Config;

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;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
     

    @Bean
    public Docket login() {
     
        return docket("测试", "com.zm.web.controller");
    }

    public Docket docket(String groupName, String basePackage) {
     
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(groupName)
                .apiInfo(apiInfo())
                .select()
                // 配置扫描接口,RequestHandlerSelectors配置如何扫描接口
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                // 配置接口过滤规则
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
     
        return new ApiInfoBuilder()
                .title("title")
                .description("description")
                .license("license")
                .licenseUrl("licenseUrl")
                .termsOfServiceUrl("termsOfServiceUrl")
                .contact(new Contact("name", "url", "email"))
                .version("version")
                .build();
    }
}

RequestHandlerSelectors配置扫描的接口

RequestHandlerSelectors.any() // 扫描所有,项目中的所有接口都会被扫描到
RequestHandlerSelectors.none() // 不扫描接口
// 通过方法上的注解扫描,如withMethodAnnotation(GetMapping.class)只扫描get请求
RequestHandlerSelectors.withMethodAnnotation(final Class<? extends Annotation> annotation)
// 通过类上的注解扫描,如.withClassAnnotation(Controller.class)只扫描有controller注解的类中的接口
RequestHandlerSelectors.withClassAnnotation(final Class<? extends Annotation> annotation)
RequestHandlerSelectors.basePackage(final String basePackage) // 根据包路径扫描接口

PathSelectors配置过滤规则

PathSelectors.any() // 任何请求都扫描
PathSelectors.none() // 任何请求都不扫描
PathSelectors.regex(final String pathRegex) // 通过正则表达式控制
PathSelectors.ant(final String antPattern) // 通过ant()控制

HttpConverterConfig

package com.zm.web.Config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class HttpConverterConfig implements WebMvcConfigurer {
     

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


    //使用阿里 FastJson 作为JSON MessageConverter
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
     
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
        supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        supportedMediaTypes.add(MediaType.APPLICATION_PDF);
        supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XML);
        supportedMediaTypes.add(MediaType.IMAGE_GIF);
        supportedMediaTypes.add(MediaType.IMAGE_JPEG);
        supportedMediaTypes.add(MediaType.IMAGE_PNG);
        supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
        supportedMediaTypes.add(MediaType.TEXT_HTML);
        supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
        supportedMediaTypes.add(MediaType.TEXT_PLAIN);
        supportedMediaTypes.add(MediaType.TEXT_XML);
        converter.setSupportedMediaTypes(supportedMediaTypes);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        FastJsonConfig config = new FastJsonConfig();
        JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
        config.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat);//格式化时间
        converter.setFastJsonConfig(config);
        // 把FastJsonHttpMessageConverter放到Jackson的前面去
        // 这个list是个ArrayList 所以我们要么就放在首位(不建议),
        // 而converters.indexOf() 因为人家是new的 所以肯定是找不到此对象的位置的 所以采用遍历的方式吧
        int jacksonIndex = 0;
        for (int i = 0; i < converters.size(); i++) {
     
            if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
     
                jacksonIndex = i;
                break;
            }
        }
        // 添加在前面
        converters.add(jacksonIndex, converter);
    }

}



常用注解

@Api(tags = "xxx模块说明")	作用在模块类上
@ApiOperation("xxx接口说明")	作用在接口方法上
@ApiModel("xxxPOJO说明")	作用在模型类上:如VO、BO
@ApiModelProperty(value = "xxx属性说明",hidden = true)作用在类方法和属性上,hidden设置为true可以隐藏该属性
@ApiParam("xxx参数说明")	作用在参数、方法和字段上,类似@ApiModelProperty

常用@ApiModelProperty注解

@ApiModelProperty(value = “”, example = “”, position = 1)
value(String) 此属性的可读概要
example(String) 举例
position(int) 在模型中显式排序属性。
required(boolean) 无论属性是否必需,默认为falseaccess(String) 指定一个可选的访问值,以便在Filter实现中进行过滤。
allowableValues(String) 如果可以设置的值受到限制,则可以在此处设置它们。
dataType 支持的数据类型
hidden(boolean) 允许在swagger模型定义中将模型属性标记为隐藏
notes(String) 长描述
name(String) 重写属性名字

API统一回调

package com.zm.common.util;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;

@ApiModel
public class ApiResult<T> implements Serializable {
     

    @ApiModelProperty(value = "回调数据")
    private T data;

    @ApiModelProperty(value = "版本号")
    private String vision;

    @ApiModelProperty(value = "状态码")
    private String code;

    @ApiModelProperty(value = "消息提示")
    private String msg;

    @ApiModelProperty(value = "数据结果集")
    public T getData() {
     
        return data;
    }

    public String getVision() {
     
        return vision;
    }

    public String getCode() {
     
        return code;
    }

    public String getMsg() {
     
        return msg;
    }

    public ApiResult<T> setData(T data) {
     
        this.data = data;
        return this;
    }

    public ApiResult<T> setVision(String vision) {
     
        this.vision = vision;
        return this;
    }

    public ApiResult<T> setCode(String code) {
     
        this.code = code;
        return this;
    }

    public ApiResult<T> setMsg(String msg) {
     
        this.msg = msg;
        return this;
    }

    /**
     * @Description    成功回调
     * @param data     回调数据
     * @param vision   版本号
     * @return
     */
    public static ApiResult successMsg(Object Object, String vision) {
     
        return new ApiResult().setCode("200").setMsg("scuess").setData(Object).setVision(vision);
    }


}

API接收或者返回的具体类

package com.zm.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel
public class User {
     
    @ApiModelProperty(value = "id")
    private Integer id;
    @ApiModelProperty(value = "姓名")
    private String name;
    @ApiModelProperty(value = "年龄")
    private Integer age;
    @ApiModelProperty(value = "爱好")
    private String skill;
    @ApiModelProperty(value = "评价")
    private String evaluate;
    @ApiModelProperty(value = "成绩")
    private Integer fraction;

}

API层

package com.zm.web.controller;

import com.zm.common.util.ApiResult;
import com.zm.entity.User;
import com.zm.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;

@RestController
public class HelloController {
     

    @Autowired
    private UserService userService;
    
    @PostMapping("/hello")
    @ApiOperation(value = "hello" ,httpMethod = "POST")
    public ApiResult<User> hello(@RequestBody User userVo) {
     
        System.out.println("请求参数:"+userVo);
        User 小明 = userService.selectUserInfoByName("小明");
        return ApiResult.successMsg(小明,"1");
    }

}

启动项目,访问地址http://127.0.0.1:8080/doc.html

springboot集成Swagger-knife4j(三)_第1张图片
springboot集成Swagger-knife4j(三)_第2张图片

配置Swagger开关

1、通过enable()方法配置是否启用swagger,如果是false,swagger将不能在浏览器中访问了

@Bean
public Docket docket() {
     
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .enable(false) //配置是否启用Swagger,如果是false,在浏览器将无法访问
      .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
      .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
       // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口
      .paths(PathSelectors.ant("/kuang/**"))
      .build();
}

2、如何动态配置当项目处于test、dev环境时显示swagger,处于prod时不显示?

@Bean
public Docket docket(Environment environment) {
     
   // 设置要显示swagger的环境
   Profiles of = Profiles.of("dev", "test");
   // 判断当前是否处于该环境
   // 通过 enable() 接收此参数判断是否要显示
   boolean b = environment.acceptsProfiles(of);
   
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .enable(b) //配置是否启用Swagger,如果是false,在浏览器将无法访问
      .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
      .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
       // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口
      .paths(PathSelectors.ant("/kuang/**"))
      .build();
}

本文章很多内容来自狂神说视频学习
狂神说Swagger学习推荐视频: https://www.bilibili.com/video/BV1PE411i7CV?p=48.

你可能感兴趣的:(springboot,java,spring,boot)