Inject Properties from Properties File using Spring Environment

We can load properties value from Properties file to Spring Environment just by using @PropertySource annotation. This tutorial shows you the simple way to get them from Environment object.

Related Articles:
Inject Properties from Properties File using @Value annotation
Inject Properties from Properties File using @ConfigurationProperties Annotation
How to use Spring Factory Method to create Spring Bean

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE (It’s OK if you use Eclipse)

II. Overview
1. Project Structure

In this example, we have 2 ways to access Properties from Environment:
– get Environment from Application Context wherever we wanna use it.
– use a seperate properties bean object to get Environment in the configuration class.

Both of them call method Environment.getProperty(“property_key”) to get property value for corresponding property_key.

2. Step to do

– Create Maven project
– Add Dependencies & Plugins
– Add Properties File
– Create Properties Class
– Create Configuration Class
– Create MainApplication Class
– Run Application & Enjoy Result

III. Practice
1. Create Maven project

– Open Spring Tool Suite, on Menu, choose File -> New -> Maven Project.
– Check Create a simple project, choose Workspace Location and click Next.
– Fill all fields in Artifact group box, then click Finish.

2. Add Dependencies & Plugins

Open pom.xml, add:

3. Add Properties File

Under src/main/resources, add properties file:

4. Create Properties Class

Under package config/properties, create

5. Create Configuration Class

Under package config, create

6. Create MainApplication Class

7. Run Application & Enjoy Result

– Config maven build:
clean install
– Run project with mode Java Application
– Check results in Console Screen:

IV. Source Code


By grokonez | October 6, 2016.

Last updated on June 4, 2017.

Related Posts

2 thoughts on “Inject Properties from Properties File using Spring Environment”

  1. So, whenever I need to use the property value On that class I need to create context and from that context, I need to retrieve property value and close the context is it?

    1. Another way is to @Autowired Environment object.

      There are other methods to get property value from property file. You can have a comparison view covering those solutions with this post:
      Inject Properties using @Value Annotations vs Environment vs @ConfigurationProperties

      Useful posts:
      Inject Properties from Properties File using @Value Annotation
      Inject Properties from Properties File using @ConfigurationProperties Annotation

      Best Regards!

Got Something To Say:

Your email address will not be published. Required fields are marked *