使用如下命令引用外部的属性文件
<context:property-placeholder location="classpath:database.properties"/>
然后使用${xxxx}的方式引用属性文件中的值
- bean-properties.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:property-placeholder location="classpath:database.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${database.driverClassName}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}" />
</bean>
</beans>
- TestSpring
package com.hgh.spring.scope;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
public static void main(String[] args) throws SQLException {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean-properties.xml");
DataSource dataSource = (DataSource) ac.getBean("dataSource");
System.out.println(dataSource.getConnection());
}
}