Swagger实现接口文档

31 阅读1分钟

一、引入依赖

  <!--添加swagger的依赖-->
 <dependency>
     <groupId>com.github.xiaoymin</groupId>
     <artifactId>knife4j-spring-boot-starter</artifactId>
     <version>2.0.7</version>
 </dependency>

二、自定义Swagger配置类

注意:线上环境不要把接口暴露出去!!!否则别人可以看你的接口,这不闹呢吗

在配置文件上使用@Profile({"dev", "test"})限定配置仅在部分环境开启

还有配置好你的controller文件地址

 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.context.annotation.Profile;
 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.EnableSwagger2WebMvc;
 ​
 /**
  * 自定义 Swagger 接口文档的配置
  */
 @Configuration
 @EnableSwagger2WebMvc
 //在哪种环境下生效
 @Profile({"dev", "test"})
 public class SwaggerConfig {
 ​
     @Bean(value = "defaultApi2")
     public Docket defaultApi2() {
         return new Docket(DocumentationType.SWAGGER_2)
                 .apiInfo(apiInfo())
                 .select()
                 // 这里一定要标注你控制器的位置
                 .apis(RequestHandlerSelectors.basePackage("com.sgx.controller"))
                 .paths(PathSelectors.any())
                 .build();
     }
 ​
     /**
      * api 信息
      * @return
      */
     private ApiInfo apiInfo() {
         return new ApiInfoBuilder()
                 .title("GX")
                 .description("接口文档")
                 .termsOfServiceUrl("https://github.com/shaogxhaha")
                 .contact(new Contact("sgx","https://github.com/shaogxhaha","xxx@qq.com"))
                 .version("1.0")
                 .build();
     }
 }
 ​

三、版本问题

如果Springboot version >= 2.6, 需要在配置文件下添加如下配置,否则项目无法启动

 spring:
   mvc:
    pathmatch:
    matching-strategy: ANT_PATH_MATCHER

四、启动

启动你的springboot项目,然后访问你的后台地址+/doc.html

比如:

 //localhost:8080/api 是我后台接口的前缀
 localhost:8080/api/doc.html