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

欣喜 Spring 发布时间:2024-01-26 11:17:15 阅读数:11052 1
下文笔者讲述Java读取Spring EL属性的读取值的方法及示例分享,如下所示
获取相关的bean 
      然后获取bean的属性
采用这种方式,即可达到读取属性的目的
例:读取mysql的配置信息
database.properties:

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

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"
       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>
 
<property name="driverClassName" value="#{database['jdbc.driverClassName']}"/>

 package org.java265.example.spring.el;

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

    // Getters & Setters
}
 
package org.java265.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("test-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/java265
username        = root
password        = secret
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/Spring/202401/7795.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者