In spring Boot applications we can define application.properites file. And in this file we can specify any properties and after that we can access these properties throughout the application.
Spring Boot provided some commonly used application properties. You can look for them here. Spring Common application properties
If we want to define our own custom properties to use in our application, we can define them.
Defining custom property by Java configuration:
- To define custom properties we need to create one POJO with the annotation @ConfigurationProperties.
- We can annotate our POJO with the @Component annotation then we no need to create @Bean for our property class explicitly in configuration classes.
- We can define some prefix for all our properties like @ConfigurationProperties(“machine.config”)
Example property POJO class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
@Component @ConfigurationProperties("machine.config") public class MachineProperties { /** * IP Address of the machine */ private String ipAddress; /** * Operating System of the machine */ private String os; /** * RAM Size */ private Integer sizeOfRAM; /** * HardDisk size */ private String sizeOfHardDisk; //setters and getters go here } |
- To enable the processing of our properties, we need to annotate any of our @Configuration class with @EnableConfigurationProperties(MachineProperties.class) like as following
Example configuration class:
1 2 3 4 5 |
@Configuration @EnableConfigurationProperties(MachineProperties.class) Public class MyAppConfig { // any configurations of application } |
Using of custom property:
Like as any other Spring common properties we can use our custom properties.
- Specify property name and its value in application.properties file.
- Access property value with the help of @Value annotation.
Example usage:
1 2 |
@Value(“${machine.config.ipAddress}”) private String ip; |
Note: SpringApplication will load properties from application.properties file by default. If you don’t like application.properties as the configuration file name you can switch to another by specifying a spring.config.name environment property like as following.
1 |
java -jar myApp.jar --spring.config.name=myAppPropertyFile |
Thank You 🙂