总结: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);
相关推荐
NE_STOP7 小时前
Vide Coding--AI编程工具的选择
java
码云数智-园园8 小时前
C++20 Modules 模块详解
java·开发语言·spring
程序员黑豆8 小时前
JDK 下载安装与配置详细教程
java·前端·ai编程
霸道流氓气质8 小时前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
小宇宙Zz8 小时前
Maven依赖冲突
java·服务器·maven
swordbob8 小时前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
于先生吖8 小时前
SpringBoot对接大模型开发AI命理测算系统:八字排盘与AI解析接口源码全解
人工智能·spring boot·后端
咖啡八杯8 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
十五喵源码网9 小时前
基于springboot2+vue2的租房管理系统
java·毕业设计·springboot·论文笔记
摇滚侠9 小时前
IDEA 创建 Java 项目 手动整合 SSM 框架
java·ide·intellij-idea