总结: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);
相关推荐
星落梦生8 小时前
SpringAOP基础笔记(7)
java·开发语言
金銀銅鐵9 小时前
带您看懂字节码指令(四):一条指令里有什么
java·jvm
最强小杰9 小时前
某 OpenAI 兼容网关上的 `kimi-k3.1-pro`:Cline、Zed 接入与 SSE 排错示例
java·服务器·网络·ai
Flynn Liang10 小时前
流量治理不是限流那么简单:I/O 密集型 Java 服务的 6 层防线
java·微服务·高并发·限流·熔断·系统稳定性·resilience4j
学长毕设10 小时前
基于SpringBoot智慧养老服务平台设计与实现-附源码
java·spring boot·后端
曹牧10 小时前
Java:“刷新雪崩”
java·开发语言
秋天的怀念_David11 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
千寻技术帮11 小时前
10454_基于Springboot的企业购销链管理系统
spring boot·mysql·vue·毕业设计·进销存
Forget the Dream12 小时前
Spring AI 2.0 系列(二):第一个 ChatClient——从注入到一次完整调用
java·人工智能·spring boot·ai·springai
行百里er13 小时前
【Spring Insight 技术分享】跨服务调用链路是怎么串起来的?
后端·spring·开源