In a Spring Boot application, properties and configuration settings can be loaded from several different sources. The order in which these properties are loaded is important because it determines which configuration will take precedence when multiple sources define the same property.
Here is the standard order of loading properties in a Spring Boot application:
- application.properties or application.yml in the config directory: Spring Boot first checks for a file named application.properties or application.yml in a config directory (which is typically located at the root of the classpath).
- application.properties or application.yml in the classpath: If the configuration is not found in the config directory, Spring Boot will then look for application.properties or application.yml files present directly on the classpath.
- Profile-specific properties: If you have configured specific profiles (like dev, test, prod, etc.), the properties files for those profiles will be loaded. They follow the naming convention application-{profile}.properties or application-{profile}.yml. These files are loaded after the main application.properties or application.yml, allowing profile-specific settings to override general ones.
- Profile-specific properties in the config directory: Similar to the previous point, Spring Boot will also consider application-{profile}.properties or application-{profile}.yml files that are located in the config directory.
- Command-line arguments: Properties specified as command-line arguments will override any settings found in the application.properties, application.yml, or any profile-specific configuration files.
- Environment variables: Environment variables take precedence over the properties file settings. For example, if you have a property defined in your configuration files and the same property defined as an environment variable, the environment variable value will be used.
- JNDI attributes: If applicable, JNDI attributes can be used to configure settings as well, and these will have a higher precedence than properties defined in files.
- System properties: Java system properties (set via the -D command-line option) also take precedence over properties in configuration files.
- Default properties: Finally, Spring Boot can provide default properties via the spring-boot-starter libraries if no other settings are specified.
To summarize the loading order:
- application.properties or application.yml in config directory
- application.properties or application.yml in classpath
- Profile-specific properties in config directory
- Profile-specific properties in classpath
- Command-line arguments
- Environment variables
- JNDI attributes
- System properties
- Default properties
This hierarchy allows developers flexibility and control over their application configuration, making it easy to override settings as needed.