在 spring-boot 或 spring 的源代码中的哪个类中处理 application.yml 或 applic



在spring-boot 或 spring 的源代码中的哪个类中处理 application.yml 文件或 application.properties ?

对于 Spring 引导(版本 2.x),应用程序属性通过 PropertySourceLoader 从环境加载到上下文中。

例如,在spring-boot-2.6.3.jar中,我们可以找到以下文件:META-INF/spring.factories

# PropertySource Loaders
org.springframework.boot.env.PropertySourceLoader=
org.springframework.boot.env.PropertiesPropertySourceLoader,
org.springframework.boot.env.YamlPropertySourceLoader

其中PropertiesPropertySourceLoader加载.properties.xml文件,YamlPropertySourceLoader加载.yml.yaml

这些加载了 SpringFactoryLoader,我们可以在org.springframework.boot.context.config.ConfigFileApplicationListener(已弃用)或org.springframework.boot.context.config.StandardConfigDataLocationResolver(通过ConfigDataEnvironmentPostProcessor->ConfigDataEnvironment->ConfigDataLocationResolvers) 中看到它的实际运行情况:

this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class,
getClass().getClassLoader());

你可以在 ConfigFileApplicationListener JavaDoc 中读到属性确实是用这个类加载的:

环境

后处理器,通过从已知文件位置加载属性来配置上下文环境。默认情况下,属性将从以下位置的"application.properties"和/或"application.yml"文件加载: 文件:./配置/文件:./配置/*/文件:。/类路径:配置/类路径: ...

如果你对 spring(boot )环境中的上下文加载感兴趣,我建议你使用 maven 设置你的项目,下载源代码 jar,并在提到的factories文件中查看一下。您将在org.springframework.boot.envorg.springframework.boot.context(configproperties)包中找到更多相关代码。

你可以在 src/main/resources 找到你的 application.yml 或 application.properties。对于每种情况,您可以为Spring Boot应用程序提供尽可能多的配置。假设您有 3 个本地配置文件,例如演示、生产和服务器,因此您进行了 3 个配置,并假设您在 application.yml 上为活动配置文件设置了演示。我希望你明白这个想法。这是在弹簧启动之前实际运行的第一件事。

请看官方文件!

最新更新