SoFunction
Updated on 2025-04-11

Implementation steps for springboot loading value file

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:

  • InitializationEnvironment: Create and initialize when the application startsEnvironmentObject.

  • Load the default configuration file: fromorLoad configuration.

  • Load Profile specific configuration files: Load according to the activated Profileapplication-{profile}.propertiesorapplication-{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 intoEnvironment, 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 initializedEnvironmentand 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 configurationEnvironmentObject.

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)StandardEnvironmentorStandardServletEnvironment

  • 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

ConfigFileApplicationListenerIt is the core class for Spring Boot loading configuration files. It monitorsApplicationEnvironmentPreparedEventEvents and loadordocument.

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 ()

LoaderyesConfigFileApplicationListenerThe 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

PropertySourcesLoaderResponsible for loading the configuration file content intoPropertySourcemiddle.

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.ProfilesandProfilePropertySourceResponsible 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: viaSpecify 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 isdev,butThe value of8081

  • If the Profile is not activated,The value of8080

5. Summary

Spring Boot has a very flexible mechanism for loading configuration files, and supports multi-source and multi-format configuration loading. passEnvironmentPropertySourceConfigFileApplicationListenerSpring 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!