简单配置 Swagger + Knife4j 接口文档

简单配置 Swagger + Knife4j 接口文档

  1. 引入依赖
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>
  1. 编写配置类
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.EnableSwagger2WebMvc;

/**
 * Swagger 配置
 */
@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {

    @Bean(value = "defaultApi2")
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.guyi.usercenter.controller"))  // 重要,标注控制器的位置
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * API 信息
     *
     * @return
     */
    public ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("")  // 设置标题
                .description("")  // 设置文档的描述
                .version("1.0")
                .contact(new Contact("孤诣", "", ""))
                .termsOfServiceUrl("")// 设置文档的 许可证 信息
                .build();
    }
}
  1. 设置 mvc 路径匹配策略
spring:
  mvc:
    pathmatch:
      matching-strategy: ANT_PATH_MATCHER
  1. 访问文档

启动项目之后访问:localhost:端口/xxx/doc.html。

  1. 隐藏接口文档

方式一
在对应的 Controller 类上添加 @profile 注解:

@Controller
@Prifile({"激活环境1", "激活环境2"})
public class TestController {}

如果项目的启动环境不在指定的激活环境中,则不会加载被标注的 Bean
这种方式比较繁琐,需要在每个 Controller 上添加 @Prifile() 注解来指定在什么环境下允许访问接口文档。

方式二
application.yml添加如下配置:

knife4j:
  enable: true
  production: true

这样所有的接口文档都无法访问。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值