Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Monday, November 4, 2019

Spring Boot: Property File Read Order

Externalization of Config file is really important in any application, however sometime it gets confusing where we should keep the property file.

By default we tend to keep the property file in "resources folder" by naming it as "application.properties(yaml/yml)" or "application-{profile}.properties(yaml/yml)".

If you have seen any existing project where they are not using default location to store the property file, however still properties are getting loaded and if you are wondering, from where the properties are read, than here are the various locations from where Spring boot by default reads the application.properties(yaml/yml) file.

Evaluation order

1st Location: Under the classpath directly: generally build tools attach the resources folder in the classpath and while running application we can add file location in the classpath using command line.

2nd Location : under the /config folder of the classpath, in other sense just see do you have any /config folder in the classpath of the project. application.properties((yaml/yml) file inside it will be loaded.

3rd Location: under the project root directory itself.

4th Location: under the /config folder of the root directory.

The order of read is exactly as par location, the last location property will override the previous location in case of conflict.


These are the default settings, you are not happy with defaults ?

Spring Boot has hook for you in that case:

1. Do you want to change the default naming of config file ( i.e. application.properties(yaml/yml)) ? You can change it to any name, just you have to set "spring.config.name" environment variable value with the name you want to give to property file.

2.  Do you want to change the default locations ? you can change it using environment variable "spring.config.location". The only thing you have to take care of, if you are providing multiple file locations, the properties in the last file in the list will override the preceding in case of conflict. One major point to note spring will not read any default locations config files in this case.

3. Do you want to read default location files as well as the custom location file ? in that case above will not work, you have to set "spring.config.additional-location" environment variable with all additional files to read. These files will have higher precedence, in case of conflict, property values from these files will override.

4. you don't want to set environment variable ? We have to use @PropertySource annotation for loading the file. The only thing is in case of conflict, properties defined in the order above will override it. It has the second lowest priority in case of conflict.

5. Let's suppose you don't have handle of the project, you have been provided with jar only, for that kind of application we can define property files in the same location where the jar is, Spring boot will load that config and add it to jar.

Evaluation order

Properties files that are placed outside of your packaged jar override the ones inside your jar. Profile-specific files always take precedence. Properties are considered in the following order:
  • Profile-specific application properties outside of your packaged jar
  • Profile-specific application properties packaged inside your jar
  • Application properties outside of your packaged jar
  • Application properties packaged inside your jar

Spring Boot: @ConfigurationProperties vs. @Value

You must have used @Value in your spring project for reading the values from property file and you have seen people started using @ConfigurationProperties to do the same.

You are wondering what exactly is the difference ?

I will try to explain.

1. You must have seen cases where the expected value type is Integer, however we supplied String expecting it will take care of conversion and bang it failed during runtime. so basically what I wanted to convey @Value is not type safe.

2. For below example, how will you load property file in you application:

    spring:
          datasource:
                   url:
                   uname:
                   pwd:
          security:
                   uname:
                   pwd:
                   role:

you must be doing

@Value("{spring.datasource.uname}")
private String dbUsername;

@Value("{spring.security.uname}")
private String securityUname;

isn't it too verbose and confusing. What I wanted to say here is @Value is too verbose and can create confusion as you have to use fully qualified name to read the property.

3. Let's suppose you have used a particular file in 30 different places in the project and suddenly need arose to change the name :), hell lot of work and not guaranteed that all changed. imagine if the property is used in hundreds of places ? What I wanted to convey @Value doesn't give any centralized mechanism to control.
4. I am not sure everyone faced this issue or not, but I am very bad at giving names. Giving name like deviceIdNumber, bulkProcessorName etc. are good if anyone is reading but not soothing to eyes. if we write like, device-id-number or bulk_processor_name, its both soothing to eyes as well as readable. What I wanted to convey @Value is not relaxing enough to allow writing property names like it. 

That's all about shortcomings in @Value, which are supported by @ConfigurationProperties apart from many other advantages.

1. @ConfigurationProperties kind of centralized all property configuration in a single class with Type binding with Setter's where you can control type conversion instead of throwing exception and log the details:

for the above example we can have 2 location to read properties, one for Datasource and one for Security:

@ConfigurationProperties(prefix="spring.datasource")
public class DatasourceConfig {
            private String uname;
            private String pwd;
            private String url;

           //setters and getters
}

@ConfigurationProperties(prefix="spring.security")
public class SecurityConfig {
            private String uname;
            private String pwd;
            private String role

           //setters and getters
}

Wherever we wanted to use those just inject the required config bean and you are done, want to change name, change it at this one place and compiler will ensure it is getting changed at all places where it is used using getter.

2. We can validate config properties using @Validate annotation in conjunction with @ConfigurationProperties annotation. we can use JSR-303 annotation directly over the fields to do the validation.

@ConfigurationProperties(prefix="spring.datasource") @Validated public class DataSourceConfig { @NotNull private String uname; // ... getters and setters }


Feature@ConfigurationProperties@Value
Yes
No
Yes
No
SpEL evaluation
No
Yes