enable()
方法 控制Swagger2 的开启与关闭
代码如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import java.util.ArrayList;
/**
* TODO
*
* @author ben
* @version 1.0
* @date 2022/9/13 11:23
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
//配置文档信息
.apiInfo(apiInfo())
//控制Swagger2的开启与关闭
.enable(true)
//扫描行为
.select()
//接口扫描 不匹配任何controller的接口
// .apis(RequestHandlerSelectors.none())
//扫描指定包路径 参数为 包路径的字符串
.apis(RequestHandlerSelectors.basePackage("cn.ben.for_learn_projects.swagger2config.controller"))
/// 任何请求都扫描
.paths(PathSelectors.any())
.build();
}
//配置文档信息
private ApiInfo apiInfo() {
Contact contact = new Contact("ben", "https://xxxxxx.com", "Swagger2Config@SpringBoot.com");
return new ApiInfo(
"Ben的学习总结", // 标题
"Swagger2Config", // 描述
"v1.0", // 版本
"https://xxxxxx.com", // 组织链接
contact, // 联系人信息
"Apach 2.0 许可", // 许可
"https://xxxxxx.com", // 许可连接
new ArrayList<>()// 扩展
);
}
}
通常,对于Swagger的配置信息,会使用一个对象(SwaggerProperties)集中配置信息,然后在SwaggerConfig
中使用该对象进行配置,而对于enable()
方法的参数,一般在开发环境为true,生产环境false,这个时候就会从yml中读取,然后在放入SwaggerConfig
中。