In this post under Spring Core, I will explain with example how to access system and environment properties.
To read system and environment properties we take help of Spring’s “Environment” interface.
The approaches to access system and environment properties are different but the “Environment” interface hides that implementation detail and provides a single interface through which we can access both.
According to “Environment” interface, the system and environment properties are called as “Property sources”.
Below is the complete main class for your reference.
Main class
1 package package35;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.context.ApplicationContext;
5 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
6 import org.springframework.context.annotation.Configuration;
7 import org.springframework.core.env.Environment;
8
9 @Configuration
10 public class Example35 {
11 @Autowired
12 private Environment environment;
13
14 public void display(String propertyKey) {
15 String result = environment.getProperty(propertyKey,"Doesn't exist");
16 System.out.println(result);
17 }
18
19 public static void main(String[] args) {
20 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example35.class);
21 Example35 example35 = applicationContext.getBean(Example35.class);
22 example35.display("java.vendor");
23 example35.display("OS");
24 }
25 }
In the above main class “Example35”, I create an instance variable “environment” of type “Environment” and request Spring to inject an instance of “Environment” class to this variable.
Then we added “display” non-static method, which takes property name as an argument from the caller and calls “getProperty” non-static method available on “Environment” class.
The “getProperty” takes two arguments
1) the property name whose value has to be retrieved
2) the default value to return, if the property requested is not present.
In the main method, I call the “display” method twice at line 22 and 23.
First call to “display” method request to get the value of property “java.vendor”.
Second call to “display” method request to get the value of property “OS”.
In a standalone environment, the “Environment” interface searches the property in system properties and environment properties. If the property is found in both places, precedence is given to system properties value.
In a web environment, more property sources are added.
In this way we can access the system and environment properties.