您的位置:首页 > 编程语言 > Java开发

Spring配置文件引入外部资源

2015-05-25 10:12 435 查看
UserDao类
public class UserDao {

private String jdbcUrl;
private String driverClass;
private String username;
private String password;
public String getJdbcUrl() {
return jdbcUrl;
}
public void setJdbcUrl(String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
}
public String getDriverClass() {
return driverClass;
}
public void setDriverClass(String driverClass) {
this.driverClass = driverClass;
}
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;
}
@Override
public String toString() {
return "UserDao [jdbcUrl=" + jdbcUrl + ", driverClass=" + driverClass
+ ", username=" + username + ", password=" + password + "]";
}


配置文件
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!--
<context:property-placeholder location="classpath:cn/com/location/jdbc.properties"/>
-->
<!--引入多个外部资源-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:cn/com/location/jdbc.properties</value>
</list>
</property>
</bean>

<bean id="userDao" class="cn.com.location.UserDao">
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
</bean>
</beans>


jdbc.properties资源文件

jdbcUrl     = jdbc:mysql://localhost:3306/tt_test
driverClass = com.mysql.jdbc.Driver
username    = root
password    = root


测试类
public class test {

@Test
public void test1(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml", this.getClass());
UserDao userDao = (UserDao) app.getBean("userDao");
System.out.println(userDao.toString());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring配置文件