Spring boot has a powerful set of annotations to read from multiple property file sources at once and capture them in POJO. Let’s see how.
In this blog, when we bootstrapped with Spring-Boot, we got one empty properties file. Create a new Java Class named DemoApplicationProperties in src/main/java/com/example/demo.
Put the following code in DemoApplicationProperties class:
package com.example.demo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Configuration
@PropertySources( {
@PropertySource("classpath:application.properties")
})
@ConfigurationProperties(prefix="prop")
public class DemoApplicationProperties {
private String url;
}
@PropertySources and @PropertySource are spring annotations. Using these annotations, we can read from any property file. The property file path has to be mentioned as an argument in @PropertySource annotation. We can have multiple properties file. All we have to do is use multiple @PropertySource annotations with the same @PropertySource annotation.
@Configuration annotation is another spring annotation. Any class with this annotation would be configured as a bean in the Spring context. Once configured as a bean we can Autowire the object of this class as a dependency injection anywhere else.
You can write as many parameters as you want in application.properties. Just make sure you are writing the corresponding variables in DemoApplicationProperties class. You would also see that I have not written any getter/setter method in DemoApplicationProperties class. Welcome to Lombok! The @Data annotation in Lombok takes care of that while reducing boilerplate code. @AllArgsConstructor and @NoArgsConstructor are other two Lombok annotations here. These do away with the need to write constructors.
Finally, @ConfigurationProperties. spring annotation lets you specify prefixes used in properties file. In our case the prefix is prop so the prefix would be ignored during variable assignment while reading from the properties file so in your application.properties file the key could be prop.url = xxxx.