您的位置:首页 > 其它

配置bean之你使用外部属性

2016-09-26 08:25 288 查看
beans-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 导入属性文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 使用外部化文件的属性 有点像el表达式-->
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="driverClass" value="${driverclass}"></property>
<property name="jdbcUrl" value="${jdbcurl}"></property>
</bean>
</beans>


在上面代码中,属性的赋值用到了.properties文件中的内容。

db.properties:

user=root
password=1230
driverclass=com.mysql.jdbc.Driver
jdbcurl=jdbc:mysql///test


.properties文件都是以键值对的形式存在。

main.java:

package com.atguigu.spring.beans.properties;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) throws SQLException {
ApplicationContext c=new ClassPathXmlApplicationContext("beans-properties.xml");

DataSource dataSource=(DataSource)c.getBean("dataSource");

System.out.println(dataSource.getConnection());

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: