springboot-Three simple ways to read properties of spring boot configuration files
1. The purpose of this post
I would demo three simple ways to read properties of spring boot configuration files..
2. Environments
springboot 1.x and 2.x
java 1.8+
3. Way 1: Read from application.properties by @Value annotation
Add these properties to your default configuration file: src/main/resources/application.properties
Use @Value like this:
Run the code ,we get this:
4. Way 2: Read from application.properties by @ConfigurationProperties annotation
Instead of @Value annotion, you can use @ConfigurationProperties,which can read some specific prefixed properties from your application.properties to your class properties.
Add these properties to your springboot application.properties
Add a class which use @ConfigurationProperties like this:
Then print properties like this:
Run the code ,we get this:
5. Way 3: Read from your custom xxx.properties by @ProperySource annotation
By reading previous sections, you can see that by using @Value or @ConfigurationProperties, it’s easy to read properties in springboot’s default application.properties, but what should we do if we want read properties from a custom properties file?
According to this document,Spring provides @PropertySource annotation to read custom file properties.
Create a new file named sysconfig.properties in src/main/resources/ , add these properties to it:
Create a new class to use the @PropertySource like this:
Print the custom properties like this:
Run the code ,we get this:
4. Conclusion
You can use @Value ,@Configuration to read default application.properties or use the @PropertySource in your custom properties file in SpringBoot apps.