简单配置 Swagger + Knife4j 接口文档
- 引入依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
- 编写配置类
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();
}
}
- 设置 mvc 路径匹配策略
spring:
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER
- 访问文档
启动项目之后访问:localhost:端口/xxx/doc.html。
- 隐藏接口文档
方式一
在对应的 Controller
类上添加 @profile
注解:
@Controller
@Prifile({"激活环境1", "激活环境2"})
public class TestController {}
如果项目的启动环境不在指定的激活环境中,则不会加载被标注的 Bean
这种方式比较繁琐,需要在每个 Controller 上添加 @Prifile()
注解来指定在什么环境下允许访问接口文档。
方式二
在 application.yml
添加如下配置:
knife4j:
enable: true
production: true
这样所有的接口文档都无法访问。