Java如何在Spring EL中读取系统环境变量?

在此示例中,以前您已经看到我们可以加载属性文件并从中读取值:如何使用Spring EL从属性文件中读取值?在此示例中,您将学习如何读取Spring EL可用的特殊属性。这些属性包括systemEnvironment和systemProperties。

该systemEnvironment属性包含运行程序的计算机上的所有环境变量。同时,systemProperties包含使用-D参数在应用程序启动时在Java中设置的所有属性。让我们看看如何在以下Spring配置文件中访问这两个属性:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="program1">
        <property name="logPath" value="#{systemProperties['APP.LOG_PATH']}"/>
    </bean>

    <bean id="program2">
        <property name="logPath" value="#{systemEnvironment['HOME']}"/>
    </bean>

</beans>

在上面的配置中,我们有两个的Program。我们logPath使用其他属性源设置属性。在program1bean中,我们使用systemProperties['APP.LOG_PATH']。使用此方法时,将在-DAPP.LOG_PATH=/Users/wayan/tmp执行程序时使用将该值传递给我们的程序。从用户的主目录属性中读取program2Bean时,该logPath属性可通过systemEnvironment变量获取。

为了使Spring配置有效,您需要使用Program类。所以这是类的定义。

package org.nhooo.example.spring.el;

public class Program {
    private String logPath;

    public Program() {
    }

    public String getLogPath() {
        return logPath;
    }

    public void setLogPath(String logPath) {
        this.logPath = logPath;
    }
}

最后,让我们创建一个简单的类来执行上面的Spring配置文件并查看代码结果。

package org.nhooo.example.spring.el;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELEnvironment {
    public static void main(String[] args) {
        ApplicationContext context =
            new ClassPathXmlApplicationContext("spel-environment.xml");

        Program program1 = (Program) context.getBean("program1");
        System.out.println("program.getLogPath() = " + program1.getLogPath());

        Program program2 = (Program) context.getBean("program2");
        System.out.println("program.getLogPath() = " + program2.getLogPath());
    }
}

该代码将打印以下结果:

program.getLogPath() = /Users/wayan/tmp
program.getLogPath() = /Users/wayan