In this post, we will learn the property loading hierarchy in Spring Boot with examples:
Property Loading Hierarchy in Spring Boot
Spring Boot provides a property loading hierarchy that allows you to override properties from different sources. This hierarchy is designed to allow you to customize your application's behavior without having to recompile your code.
The property loading hierarchy is as follows:
1. Command line arguments
2. Java System properties
3. OS environment variables
4. Properties files in the `src/main/resources` directory
5. Properties files in the `classpath`
6. Default properties
You can override properties from higher levels in the hierarchy by providing the same property with a different value in a lower level. For example, you can override a property that is defined in a `.properties` file by providing the same property with a different value on the command line.
Examples
Here are some examples of how to override properties in the property loading hierarchy:
To override a property that is defined in a `.properties` file, you can provide the same property with a different value on the command line. For example, if you have a `.properties` file that defines the property `my.property=foo`, you can override this property by running the following command:
java -Dmy.property=bar MyApplication
To override a property that is defined in a `.properties` file using an environment variable, you can set the environment variable with the same name as the property. For example, if you have a `.properties` file that defines the property `my.property=foo`, you can override this property by setting the environment variable `MY_PROPERTY` to `bar`.
export MY_PROPERTY=barjava MyApplication
To override a property that is defined in a `.properties` file using a property annotation, you can annotate a field with the `@Value` annotation and specify the property name. For example, if you have a `.properties` file that defines the property `my.property=foo`, you can override this property by annotating a field with the following annotation:
@Value("${my.property}")private String myProperty;
Default Properties
Spring Boot also provides a set of default properties that can be overridden. These properties are located in the `spring.properties` file in the `src/main/resources` directory.
You can override default properties by providing the same property with a different value in a `.properties` file, on the command line, or using an environment variable.
Conclusion
The property loading hierarchy in Spring Boot allows you to override properties from different sources. This hierarchy is designed to allow you to customize your application's behavior without having to recompile your code.
I hope this blog post has been helpful. Please let me know if you have any questions.
Tags:
spring boot