springboot加載配值文件的實現(xiàn)步驟
Spring Boot 加載配置文件的機制是其核心功能之一,它通過一系列源碼實現(xiàn)從不同來源加載配置,并支持靈活的配置管理。以下是 Spring Boot 加載配置文件的源碼解析及其實現(xiàn)原理的詳細說明。(下述兩段是加載配置文件的源碼片段)
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { this.sources = new LinkedHashSet(); this.bannerMode = Mode.CONSOLE; this.logStartupInfo = true; this.addCommandLineProperties = true; this.addConversionService = true; this.headless = true; this.registerShutdownHook = true; this.additionalProfiles = Collections.emptySet(); this.isCustomEnvironment = false; this.lazyInitialization = false; this.applicationContextFactory = ApplicationContextFactory.DEFAULT; this.applicationStartup = ApplicationStartup.DEFAULT; this.resourceLoader = resourceLoader; Assert.notNull(primarySources, "PrimarySources must not be null"); this.primarySources = new LinkedHashSet(Arrays.asList(primarySources)); //1.推測web應用類型(NONE REACTIVE SERVLET) this.webApplicationType = WebApplicationType.deduceFromClasspath(); //2.從spring.factories中獲取BootstrapRegistryInitializer對象 this.bootstrapRegistryInitializers = this.getBootstrapRegistryInitializersFromSpringFactories(); //3.從spring.factories中獲取ApplicationContextInitializer對象 this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class)); //4.從spring.factories中獲取ApplicationListener對象 this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class)); //5.推測出Main類 (main()方法所在的類) this.mainApplicationClass = this.deduceMainApplicationClass(); }
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); DefaultBootstrapContext bootstrapContext = this.createBootstrapContext(); ConfigurableApplicationContext context = null; this.configureHeadlessProperty(); /**從spring.factories中獲取SpringApplicationRunListeners 對象 * 默認會拿到一個EventPublishingRunListener ,他會啟動過程的各個階段發(fā)布對應的事件 **/ SpringApplicationRunListeners listeners = this.getRunListeners(args); listeners.starting(bootstrapContext, this.mainApplicationClass); try { //將run()的參數(shù)封裝為DefaultApplicationArguments對象 ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); //配置文件的入口 ConfigurableEnvironment environment = this.prepareEnvironment(listeners, bootstrapContext, applicationArguments); this.configureIgnoreBeanInfo(environment); Banner printedBanner = this.printBanner(environment); //根據(jù)應用類型創(chuàng)建Spring容器 context = this.createApplicationContext(); context.setApplicationStartup(this.applicationStartup); this.prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner); //刷新Spring容器, 會解析配置類 掃描 啟動Webserver this.refreshContext(context); this.afterRefresh(context, applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch); } listeners.started(context); //調用applicationArguments 和CommandLineRunner this.callRunners(context, applicationArguments); } catch (Throwable var10) { this.handleRunFailure(context, var10, listeners); throw new IllegalStateException(var10); } try { listeners.running(context); return context; } catch (Throwable var9) { this.handleRunFailure(context, var9, (SpringApplicationRunListeners)null); throw new IllegalStateException(var9); } }
1. Spring Boot 加載配置文件的整體流程
Spring Boot 加載配置文件的流程可以分為以下幾個步驟:
初始化
Environment
:在應用啟動時,創(chuàng)建并初始化Environment
對象。加載默認配置文件:從
application.properties
或application.yml
加載配置。加載 Profile 特定的配置文件:根據(jù)激活的 Profile 加載
application-{profile}.properties
或application-{profile}.yml
。加載外部化配置:從命令行參數(shù)、環(huán)境變量、JNDI 等外部來源加載配置。
合并配置:將所有配置來源合并到
Environment
中,供應用程序使用。
2. 源碼解析
以下是 Spring Boot 加載配置文件的核心源碼解析。
2.1 SpringApplication.run()
Spring Boot 應用的啟動入口是 SpringApplication.run()
方法。在這個方法中,會初始化 Environment
并加載配置文件。
源碼位置:org.springframework.boot.SpringApplication
public ConfigurableApplicationContext run(String... args) { // ... ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); // ... }
說明:
prepareEnvironment()
方法負責創(chuàng)建和配置Environment
對象。
2.2 prepareEnvironment()
prepareEnvironment()
方法會調用 configureEnvironment()
來加載配置文件。
源碼位置:org.springframework.boot.SpringApplication
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) { // 創(chuàng)建 Environment 對象 ConfigurableEnvironment environment = getOrCreateEnvironment(); // 配置 Environment,加載配置文件 configureEnvironment(environment, applicationArguments.getSourceArgs()); // 觸發(fā)環(huán)境準備事件 listeners.environmentPrepared(environment); // 將 Environment 綁定到 SpringApplication bindToSpringApplication(environment); return environment; }
說明:
getOrCreateEnvironment()
:根據(jù)應用類型(Web 或非 Web)創(chuàng)建StandardEnvironment
或StandardServletEnvironment
。configureEnvironment()
:加載配置文件和其他外部化配置。
2.3 configureEnvironment()
configureEnvironment()
方法會調用 configurePropertySources()
和 configureProfiles()
來加載配置文件和激活 Profile。
源碼位置:org.springframework.boot.SpringApplication
protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) { configurePropertySources(environment, args); configureProfiles(environment, args); }
說明:
configurePropertySources()
:加載命令行參數(shù)、默認配置文件等。configureProfiles()
:設置激活的 Profile。
2.4 ConfigFileApplicationListener
ConfigFileApplicationListener
是 Spring Boot 加載配置文件的核心類。它監(jiān)聽 ApplicationEnvironmentPreparedEvent
事件,并加載 application.properties
或 application.yml
文件。
源碼位置:org.springframework.boot.context.config.ConfigFileApplicationListener
public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationEnvironmentPreparedEvent) { onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event); } }
說明:
onApplicationEnvironmentPreparedEvent()
:在環(huán)境準備完成后觸發(fā),加載配置文件。
2.5 Loader.load()
Loader
是 ConfigFileApplicationListener
的內部類,負責實際加載配置文件。
源碼位置:org.springframework.boot.context.config.ConfigFileApplicationListener.Loader
void load() { for (String location : getSearchLocations()) { for (String name : getSearchNames()) { load(location, name); } } }
說明:
getSearchLocations()
:獲取配置文件的搜索路徑(如classpath:/
、file:./config/
等)。getSearchNames()
:獲取配置文件的名稱(如application
)。load(location, name)
:從指定路徑加載配置文件。
2.6 PropertySourcesLoader
PropertySourcesLoader
負責將配置文件內容加載到 PropertySource
中。
源碼位置:org.springframework.boot.env.PropertySourcesLoader
public PropertySource<?> load(Resource resource) throws IOException { if (resource.getFilename().endsWith(".yml")) { return loadYaml(resource); } else { return loadProperties(resource); } }
說明:
loadYaml()
:加載 YAML 格式的配置文件。loadProperties()
:加載 Properties 格式的配置文件。
2.7 Profile 的加載
Spring Boot 支持通過 Profile 加載不同的配置文件。Profiles
和 ProfilePropertySource
負責處理 Profile 相關的配置。
源碼位置:org.springframework.core.env.Profiles
public static Profiles of(String... profiles) { return new Profiles() { @Override public boolean matches(Predicate<String> predicate) { // ... } }; }
說明:
Profiles
:管理 Profile 的激活狀態(tài)。ProfilePropertySource
:根據(jù)激活的 Profile 加載特定的配置文件。
3.Spring Boot配置文件的實現(xiàn)原理
Spring Boot 加載配置文件的實現(xiàn)原理可以總結為以下幾點:
- 多來源加載:支持從類路徑、外部目錄、環(huán)境變量、命令行參數(shù)等多種來源加載配置。
- 優(yōu)先級機制:后加載的配置會覆蓋先加載的配置,命令行參數(shù)的優(yōu)先級最高。
- Profile 支持:通過
spring.profiles.active
指定激活的 Profile,加載對應的配置文件。 - 外部化配置:支持從外部文件、環(huán)境變量、JNDI 等加載配置,適用于云原生和容器化部署。
4. 示例:Spring Boot 加載配置文件的流程
以下是一個完整的示例,展示 Spring Boot 如何加載配置文件。
4.1 默認配置文件
application.properties:
server.port=8080 spring.profiles.active=dev
4.2 Profile 特定的配置文件
application-dev.properties:
server.port=8081
4.3 Java 代碼
@RestController public class MyController { ? @Value("${server.port}") private String port; ? @GetMapping("/port") public String getPort() { return "Server port: " + port; } }
4.4 運行結果
如果激活的 Profile 是
dev
,則server.port
的值為8081
。如果沒有激活 Profile,則
server.port
的值為8080
。
5. 總結
Spring Boot 加載配置文件的機制非常靈活,支持多來源、多格式的配置加載。通過 Environment
、PropertySource
、ConfigFileApplicationListener
等核心類和組件,Spring Boot 實現(xiàn)了配置文件的加載、合并和優(yōu)先級管理。理解這些源碼和機制,可以幫助我們更好地使用和擴展 Spring Boot 的配置功能。
到此這篇關于springboot加載配值文件的實現(xiàn)步驟的文章就介紹到這了,更多相關springboot加載配值文件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- springboot無法加載yml配置文件的解決方案
- SpringBoot使用不同環(huán)境動態(tài)加載不同配置文件
- SpringBoot配置文件啟動加載順序的方法步驟
- SpringBoot配置文件的優(yōu)先級順序、加載順序、bootstrap.yml與application.yml區(qū)別及說明
- SpringBoot項目部署時application.yml文件的加載優(yōu)先級和啟動腳本問題
- SpringBoot中的配置文件加載優(yōu)先級詳解
- SpringBoot加載不出來application.yml文件的解決方法
- SpringBoot項目加載配置文件的6種方式小結
- SpringBoot實現(xiàn)配置文件自動加載和刷新的示例詳解
- SpringBoot的配置文件application.yml及加載順序詳解
相關文章
Spring Boot中的那些條件判斷的實現(xiàn)方法
這篇文章主要介紹了Spring Boot中的那些條件判斷的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04Spring ApplicationContextAware 接口的作用及使用方式
Spring提供了許多回調接口,用于Bean生命周期中執(zhí)行特定的操作,通過實現(xiàn)ApplicationContextAware接口,Spring提供了一種便捷的方式讓 Bean獲取對Spring容器的引用,本文介紹ApplicationContextAware接口的作用、使用方式,以及在實際應用中的常見場景,感興趣的朋友一起看看吧2024-01-01IntelliJ?IDEA?代碼運行時中文出現(xiàn)亂碼問題及解決方法
在我們剛接觸到IDEA時,想美滋滋的敲一個“hello?world”來問候這個世界,但難免會遇到這種問題亂碼,這篇文章主要介紹了解決IntelliJ?IDEA?代碼運行時中文出現(xiàn)亂碼問題,需要的朋友可以參考下2023-09-09Java兩整數(shù)相除向上取整的方式詳解(Math.ceil())
在調外部接口獲取列表數(shù)據(jù)時,需要判斷是否已經(jīng)取完了所有的值,因此需要用到向上取整,下面這篇文章主要給大家介紹了關于Java兩整數(shù)相除向上取整的相關資料,需要的朋友可以參考下2022-06-06