Java如何使用Spring EL从属性文件中读取值?

在前面的两个示例中,您已经了解了如何使用[]Spring EL中的方括号运算符访问集合的成员和访问映射元素。在此示例中,您将看到如何使用[]运算符从属性文件或中读取值java.util.Properties。

假设我们有一个名为的数据库属性文件,database.properties其中包含以下条目:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/nhooo
jdbc.username=root
jdbc.password=secret

首先,让我们创建spring配置文件。在此配置中,我们将使用<util:properties>将属性配置加载到Spring中。然后,我们将使用Spring EL访问此属性的值,并将其分配给某些bean的属性。

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

    <util:properties id="database" location="classpath:database.properties"/>

    <bean id="dataSource">
        <property name="driverClassName" value="#{database['jdbc.driverClassName']}"/>
        <property name="url" value="#{database['jdbc.url']}"/>
        <property name="username" value="#{database['jdbc.username']}"/>
        <property name="password" value="#{database['jdbc.password']}"/>
    </bean>
</beans>

要从属性文件中读取值,您所要做的与我们访问映射对象元素的方式相同。我们将属性名称作为键传递给Spring EL。

<property name="driverClassName" value="#{database['jdbc.driverClassName']}"/>

所述MyDataSource类是虚数据源对象。它有一些属性,如driverClassName,url,username和password。这是使用JDBC驱动程序连接数据库的常用参数。为简单起见,我们从类中删除了获取器和设置器。

package org.nhooo.example.spring.el;

public class MyDataSource {
    private String driverClassName;
    private String url;
    private String username;
    private String password;

    // Getters & Setters
}

和往常一样,要运行上面的Spring配置,我们将需要创建一个主类来加载和执行应用程序上下文。此类将从应用程序上下文中获取dataSource bean,并打印出其属性,这些属性的值是从名为database.properties的属性文件中读取的。

package org.nhooo.example.spring.el;

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

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

        MyDataSource dataSource = (MyDataSource) context.getBean("dataSource");
        System.out.println("driverClassName = " + dataSource.getDriverClassName());
        System.out.println("url             = " + dataSource.getUrl());
        System.out.println("username        = " + dataSource.getUsername());
        System.out.println("password        = " + dataSource.getPassword());
    }
}

这是运行代码片段时得到的结果:

driverClassName = com.mysql.jdbc.Driver
url             = jdbc:mysql://localhost/nhooo
username        = root
password        = secret