Spring Boot loads configuration files mechanism is one of its core functions. It uses a series of source code to load configurations from different sources and supports flexible configuration management. The following is a detailed description of the source code analysis and implementation principles of Spring Boot loading configuration files. (The following two paragraphs are source code fragments that load the configuration file)
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { = new LinkedHashSet(); = ; = true; = true; = true; = true; = true; = (); = false; = false; = ; = ; = resourceLoader; (primarySources, "PrimarySources must not be null"); = new LinkedHashSet((primarySources)); //1. Inferred web application type (NONE REACTIVE SERVLET) = (); //2. Get BootstrapRegistryInitializer object from it = (); //3. Get the ApplicationContextInitializer object from it (()); //4. Get ApplicationListener object from it (()); //5. Inferred that Main class (the class where the main() method is located) = (); }
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); (); DefaultBootstrapContext bootstrapContext = (); ConfigurableApplicationContext context = null; (); /**Get SpringApplicationRunListeners object from it * By default, you will get an EventPublishingRunListener, which will start the process and publish the corresponding events at each stage. **/ SpringApplicationRunListeners listeners = (args); (bootstrapContext, ); try { //Encapsulate the parameters of run() as a DefaultApplicationArguments object ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); //The entry of the configuration file ConfigurableEnvironment environment = (listeners, bootstrapContext, applicationArguments); (environment); Banner printedBanner = (environment); //Create Spring container according to application type context = (); (); (bootstrapContext, context, environment, listeners, applicationArguments, printedBanner); //Refresh the Spring container and resolve the configuration class. Scan to start the Webserver. (context); (context, applicationArguments); (); if () { (new StartupInfoLogger()).logStarted((), stopWatch); } (context); //Call applicationArguments and CommandLineRunner (context, applicationArguments); } catch (Throwable var10) { (context, var10, listeners); throw new IllegalStateException(var10); } try { (context); return context; } catch (Throwable var9) { (context, var9, (SpringApplicationRunListeners)null); throw new IllegalStateException(var9); } }
1. The overall process of loading configuration files in Spring Boot
The process of loading configuration files in Spring Boot can be divided into the following steps:
Initialization
Environment
: Create and initialize when the application startsEnvironment
Object.Load the default configuration file: from
or
Load configuration.
Load Profile specific configuration files: Load according to the activated Profile
application-{profile}.properties
orapplication-{profile}.yml
。Load external configuration: Load configuration from external sources such as command line parameters, environment variables, JNDI, etc.
Merge configuration: Merge all configuration sources into
Environment
, supplying applications.
2. Source code analysis
The following is the core source code analysis of Spring Boot loading configuration files.
2.1 ()
The startup portal of Spring Boot application is()
method. In this method, it will be initializedEnvironment
and load the configuration file.
Source code location:
public ConfigurableApplicationContext run(String... args) { // ... ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); // ... }
illustrate:
prepareEnvironment()
Methods are responsible for creation and configurationEnvironment
Object.
2.2 prepareEnvironment()
prepareEnvironment()
The method will be calledconfigureEnvironment()
To load the configuration file.
Source code location:
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) { // Create Environment object ConfigurableEnvironment environment = getOrCreateEnvironment(); // Configure Environment and load configuration files configureEnvironment(environment, ()); // Trigger environment preparation event (environment); // Bind Environment to SpringApplication bindToSpringApplication(environment); return environment; }
illustrate:
getOrCreateEnvironment()
: Created according to application type (Web or non-Web)StandardEnvironment
orStandardServletEnvironment
。configureEnvironment()
: Load configuration files and other external configurations.
2.3 configureEnvironment()
configureEnvironment()
The method will be calledconfigurePropertySources()
andconfigureProfiles()
To load the configuration file and activate the Profile.
Source code location:
protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) { configurePropertySources(environment, args); configureProfiles(environment, args); }
illustrate:
configurePropertySources()
: Load command line parameters, default configuration files, etc.configureProfiles()
: Set the activated profile.
2.4 ConfigFileApplicationListener
ConfigFileApplicationListener
It is the core class for Spring Boot loading configuration files. It monitorsApplicationEnvironmentPreparedEvent
Events and loador
document.
Source code location:
public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationEnvironmentPreparedEvent) { onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event); } }
illustrate:
onApplicationEnvironmentPreparedEvent()
: Triggered after the environment is ready and load the configuration file.
2.5 ()
Loader
yesConfigFileApplicationListener
The internal class is responsible for actually loading the configuration file.
Source code location:
void load() { for (String location : getSearchLocations()) { for (String name : getSearchNames()) { load(location, name); } } }
illustrate:
getSearchLocations()
: Get the search path of the configuration file (such asclasspath:/
、file:./config/
wait).getSearchNames()
: Get the name of the configuration file (such asapplication
)。load(location, name)
: Load the configuration file from the specified path.
2.6 PropertySourcesLoader
PropertySourcesLoader
Responsible for loading the configuration file content intoPropertySource
middle.
Source code location:
public PropertySource<?> load(Resource resource) throws IOException { if (().endsWith(".yml")) { return loadYaml(resource); } else { return loadProperties(resource); } }
illustrate:
loadYaml()
: Load the configuration file in YAML format.loadProperties()
: Load the Properties format configuration file.
2.7 Profile loading
Spring Boot supports loading different configuration files through Profile.Profiles
andProfilePropertySource
Responsible for handling Profile-related configurations.
Source code location:
public static Profiles of(String... profiles) { return new Profiles() { @Override public boolean matches(Predicate<String> predicate) { // ... } }; }
illustrate:
Profiles
: Manage the activation status of the Profile.ProfilePropertySource
: Load a specific configuration file according to the activated profile.
The implementation principle of Boot configuration file
The implementation principle of Spring Boot loading configuration files can be summarized as follows:
- Multi-source loading: supports loading configurations from classpaths, external directories, environment variables, command line parameters, etc.
- Priority mechanism: The configuration loaded later will override the configuration loaded first, and the command line parameters have the highest priority.
- Profile support: via
Specify the activated profile to load the corresponding configuration file.
- External configuration: Supports loading configurations from external files, environment variables, JNDI, etc., suitable for cloud-native and containerized deployments.
4. Example: The process of loading configuration files in Spring Boot
Here is a complete example showing how Spring Boot loads configuration files.
4.1 Default configuration file
:
=8080 =dev
4.2 Profile specific configuration files
:
=8081
4.3 Java code
@RestController public class MyController { @Value("${}") private String port; @GetMapping("/port") public String getPort() { return "Server port: " + port; } }
4.4 Operation results
If the activated Profile is
dev
,butThe value of
8081
。If the Profile is not activated,
The value of
8080
。
5. Summary
Spring Boot has a very flexible mechanism for loading configuration files, and supports multi-source and multi-format configuration loading. passEnvironment
、PropertySource
、ConfigFileApplicationListener
Spring Boot implements the loading, merging and priority management of configuration files. Understanding these source codes and mechanisms can help us better use and extend Spring Boot's configuration features.
This is the article about the implementation steps of springboot loading value file. For more related contents of springboot loading value file, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!