一、SPI示例1-Swagger
引用
https://zhuanlan.zhihu.com/p/444331676
在java spring cloud项目中,我们常常会在子模块中创建公共方法,
那么在另外一个子模块中,需要加载配置文件的时候,
往往Spring Boot 自动扫描包的时候,只会扫描自己模块下的类。这个是springboot约定俗成的内容。
对扩展开放,对修改关闭的原则。
1.1 背景介绍
Swagger 作为一基础工具,在各个子项目中都需要使用。因此需将该功能放入Common项目中,以此做到谁依赖谁即用的便捷使用方式。在一个父项目中,有子项目AOP,Common。Common中集成了swagger,AOP项目添加Common这个依赖就可以直接使用swagger这个功能了。
1.2 实现
1.2.1 子项目Common中 Swagger配置
@Configuration //注解添加Config到SpringBoot中
@EnableSwagger2 //开启Swagger2
@EnableKnife4j
public class SwaggerConfig {
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//分组名称
.groupName("1.0")
.select()
//代表只扫描api下的接口
// .apis(RequestHandlerSelectors.basePackage("com.sqa.bc.PipingCollectionPluginCommon.api"))
// .apis(RequestHandlerSelectors.basePackage("com.sqa.bc"))
.apis(RequestHandlerSelectors.basePackage("com"))
.paths(PathSelectors.any())
.build();
return docket;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("采集任务管理与过程监控分系统")
.description("API文档")
.version("1.0")
.build();
}
// //配置Swagger的Docket的Bean实例
// @Bean
// public Docket docket(){
// return new Docket(DocumentationType.SWAGGER_2)
// .apiInfo(apiInfo());
// }
//
// //配置Swagger 信息 --》 apiInfo
// private ApiInfo apiInfo(){
//
// //作者信息
// Contact contact = new Contact("hwh", "https://blog.csdn.net/kelekele111?type=blog", "123");
//
// return new ApiInfo(
// "哈哈哈哈",
// "Api----Swagger----Demo",
// "1.0",
// "https:xxxx",
// contact,
// "Apache 2.0",
// "http://www.apache.org/licenses/LICENSE-2.0",
// new ArrayList());
// }
}
1.2.2 测试子项目Common的Swagger功能可用情况
可用
1.2.3 测试子项目AOP的Swagger功能可用情况
不可用
1.2.4 在子项目AOP的启动类上添加注解
在子项目AOP的启动类上添加如下注解:
@Import(value = {SwaggerConfig.class})
1.2.5 测试子项目AOP的Swagger功能可用情况
可用
1.2.6 子项目Common中添加spring.factories配置文件
将子项目AOP启动类上的@Import(value = {SwaggerConfig.class})注解删除
添加如下配置:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.sqa.bc.PipingCollectionPluginCommon.config.SwaggerConfig
1.2.7测试子项目AOP的Swagger功能可用情况
在子项目Common中添加spring.factories配置文件的基础上再次测试子项目AOP的Swagger功能可用情况
结果为 可用
1.2. 8结论
子项目Common中仅仅做1.2.1的配置,在子项目AOP中swagger功能是不可用的。需要在子项目Common中做1.2.4配置,这时在子项目AOP中swagger功能是可用的。
在日常工作中,我们可能需要实现一些SDK 或者Sring boot starter 给别人用的时候,我们就可以使用Factories机制,Factories机制可以让SDK或者Stater的使用只需要很少或者不需要进行配置,只需要在服务中引入我们的Jar包就即可。
参考:
springboot核心基础之spring.factories机制
spring的spi
SpringBoot集成swagger