Spring Boot Reading Properties File

Points To Remember


  • You can use @PropertySource annotation to load the properties file from classpath.
  • Keep your properties file under the resources folder.
  • Use @Value annotation to load the values from property file with "${key}" as key.

Load Properties file from classpath in Spring boot.

Your properties file look like following.

spring.data1=sampleData1
spring.data2=sampleData2
spring.data3=sampleData3

You can load the properties using the following two approaches

  1. In this approach you can specify a prefix with which your config starts in the properties file
    @Component
    @PropertySource("sample.properties")
    @ConfigurationProperties(prefix = "spring")
    public class SampleConfig {
    
        private String data1;
        private String data2;
        private String data3;
       
        // GETTERS and SETTERS
    
    }
  2. In this approach you need to specify the whole key to read the value from the properties file.
    @Component
    @PropertySource(value = "sample.properties")
    public class SampleConfig {
    
        @Value("${spring.data1}")
        private String data1;
    
        @Value("${spring.data2}")
        private String data2;
    
        @Value("${spring.data3}")
        private String data3;
    
        // GETTERS and SETTERS
    
    }

  • If your properties file is under resources folder, then you so not need to use @PropertySource annotation.
  • To read the file and assign value you need to use ${} delimiter. Without this your values will not be assigned to the class property.
  • These values cannot be assigned to the static fields.


Both of the above methods can be used and can be autowired to get the values from the properties file corresponding to the keys.

No comments :

Post a Comment