我们在开发数据库项目时,会将数据库的连接放入属性文件中,这时我们需要使用spring中提供的PropertyPlacholderConfigurer类,将属性文件中的值取出来注入类的属性中
applicationContext中使用PropertyPlacholderConfigurer类将properties从classpath路径加载到内存中,然后通过${}的方式,指定属性文件中的key来将属性文件中的value注入到Test的属性中
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="property"
class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="locations">
<list>
<value>dbconfig.properties</value>
</list>
</property>
</bean>
<bean id="properties" class="com.test.Test">
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<property name="url" value="${url}"/>
<property name="driver" value="${driver}"/>
</bean>
</beans>
Test
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
String username;
String password;
String url;
String driver;
public static void main(String[] args) {
//取得应用程序上下文接口
ApplicationContext apl = new ClassPathXmlApplicationContext("applicationContext.xml");
Test getprop = (Test) apl.getBean("properties");
System.out.println("username:"+getprop.username);
System.out.println("password:"+getprop.password);
System.out.println("url:"+getprop.url);
System.out.println("driver:"+getprop.driver);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
}
properties
username = root
password = 1234
url = jdbc:mysql://localhost:3306
driver =com.mysql.jdbc.Driver