In this post, I will demonstrate three simple ways to read properties files into spring boot applications,including the @Value ,@Configuration and @PropertySource annotations.
2. Environments
springboot
java 1.8+
3. Way 1: Read from application.properties by @Value annotation
Add these properties to your default configuration file:
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 spring boot 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:
6. Conclusion
You can use @Value ,@Configuration to read default application.properties or use the @PropertySource in your custom properties file in SpringBoot apps.
Final Words + More Resources
My intention with this article was to help others who might be considering solving such a problem.
So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by
email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope: