总结:Spring Boot 之spring.factories

一、介绍

Spring IOC会将所有的对象交由Spring管理,扫描对象是在Spring boot的路径下的所有配置类注解,需要管理的对象。

但是:如果这些Bean路径不在Spring Boot的包扫描路径下,怎么办?这样不就实例化不了了吗?

有两种方式解决这个问题:

方式一:通过在启动类中加上@Import注解,以 SwaggerConfig 为例。
复制代码
@Configuration
@EnableSwagger2
public class SwaggerConfig implements EnvironmentAware {
    private static final Logger log = LoggerFactory.getLogger(SwaggerConfig.class);
    @Autowired
    private Environment env;
    @Value("${swagger.scan.package}")
    private String swaggerScanPackage;

    public SwaggerConfig() {
    }

    @Bean
    public Docket createRestApi() {
        Predicate<String> path = PathSelectors.any();
        if (Arrays.asList(this.env.getActiveProfiles()).contains("prod")) {
            path = PathSelectors.none();
        }

        return (new Docket(DocumentationType.SWAGGER_2)).apiInfo(this.apiInfo()).select().apis(RequestHandlerSelectors.basePackage(this.swaggerScanPackage)).paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo() {
        return (new ApiInfoBuilder()).title("APIs").description("............").termsOfServiceUrl("https://js.dazhi.loan.com").version("1.0").build();
    }

    @Override
    public void setEnvironment(Environment environment) {

    }
}

启动类上加上@Import注解,如下:

但是有个问题,当这类配置比较多的时候,启动类会很繁琐。

方式二:使用spring.factories

采用spring.factories 的方式去加载SwaggerConfig类,在resources目录下新建一个META-INF 的目录,然后在

新建一个spring.factories 的文件,里面的内容为:

复制代码
org.springframework.boot.autoconfigure.EnableAutoConfiguration=

com.sg.config.SwaggerConfig

这样也可以加载到SwaggerConfig。

二、spring.factories加载使用

Spring boot使用SpringFactoriesLoader来加载spring.factories。

可通过Spring boot启动源码的获取监听器方法查看。

根据对下面代码的追踪可知,最终是通过读取META-INF/spring.factories读取里面的监听器类然后做响应的操作。

复制代码
SpringApplicationRunListeners listeners = getRunListeners(args);
相关推荐
QC班长5 小时前
Maven公司私库配置踩坑点
java·服务器·maven·intellij-idea
Makoto_Kimur5 小时前
java开发面试-AI Coding速成
java·开发语言
wuqingshun3141595 小时前
说说mybatis的缓存机制
java·缓存·mybatis
空中海6 小时前
Kubernetes 生产实践、可观测性与扩展入门
java·贪心算法·kubernetes
Devin~Y6 小时前
大厂Java面试实录:Spring Boot/Cloud、Kafka、Redis、K8s 与 Spring AI(RAG/Agent)三轮连环问
java·spring boot·redis·mysql·spring cloud·kafka·kubernetes
bLEd RING6 小时前
SpringBoot3.3.0集成Knife4j4.5.0实战
java
小松加哲6 小时前
Spring MVC 核心原理全解析
java·spring·mvc
Ulyanov7 小时前
《PySide6 GUI开发指南:QML核心与实践》 第二篇:QML语法精要——构建声明式UI的基础
java·开发语言·javascript·python·ui·gui·雷达电子对抗系统仿真
码界筑梦坊7 小时前
357-基于Java的大型商场应急预案管理系统
java·开发语言·毕业设计·知识分享
云烟成雨TD7 小时前
Spring AI Alibaba 1.x 系列【31】集成 Studio 模块实现可视化 Agent 调试
java·人工智能·spring