Java中Spring EL中如何读取系统环境变量呢?
下文笔者讲述spring EL表达式中读取系统环境变量的方法及示例分享,如下所示
1.如果el表达式中放入systemEnvironment 时 则spring会自动读取系统环境变量 2.如果读取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> package com.java265.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 com.java265.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/test/tmp program.getLogPath() = /Users/test
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。