Java如何使用Spring EL属性文件中读取值?
下文笔者讲述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
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。