In Spring applications, there may be a need to read and use environment variables from the operating system. This is especially useful when managing application configurations based on different environments, such as development, QA, and production.
To read a system environment variable in Spring 3.0, the Spring Expression Language (SpEL) can be utilized. Here's how it can be achieved:
<code class="xml"><util:properties id="dbProperties" location="classpath:config_#{systemProperties['env']}/db.properties" /></code>
In this configuration, the property file to be loaded is dynamically selected based on the value of the env system environment variable. When starting the application, you can specify the environment using the -D command-line argument, such as:
<code class="bash">java -Denv=QA ...</code>
Note: For accessing OS-level environment variables directly, you can use systemEnvironment instead of systemProperties in the SpEL expression, like:
<code class="xml"><util:properties id="dbProperties" location="classpath:config_#{systemEnvironment['ENV_VARIABLE_NAME']}/db.properties" /></code>
The above is the detailed content of How to Read System Environment Variables in Spring Application Context?. For more information, please follow other related articles on the PHP Chinese website!