【Spring4.0】配置Bean时使用外部属性文件properties连接MySQL

##一、为什么要在配置bean时使用外部属性文件properties?

一般来说,我们可以直接在bean中直接配置连接数据库的相关参数如下所示:
bean配置文件beans-properties.xml

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		p:user="root" 
		p:password="123456" 
		p:driverClass="com.mysql.jdbc.Driver"
		p:jdbcUrl="jdbc\:mysql\://localhost\:3306/test"></bean>

主方法Main.java

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-properties.xml");
		DataSource dataSource = (DataSource) ctx.getBean("dataSource");
		System.out.println(dataSource.getConnection());

结果(能够正常运行):
这里写图片描述
可是假如spring的配置文件里面有许多bean,这样文件大的话找到配置数据源的地方进行修改不方便。因此基本信息最好拿出来部署到属性文件(properties)里面最好。



##二、如何做到配置Bean时使用外部属性文件properties?

###1.导入驱动
需要导入相关的数据库驱动

这里写图片描述
###2.添加属性文件db.properties
注意!!
db.properties存放在src根目录下

user=root
password=123456
driverclass=com.mysql.jdbc.Driver
jdbcurl=jdbc\:mysql\://localhost\:3306/test

###3.在beans-properties.xml中通过<context:property-placeholder>引用外部配置文件
注意!!
要导入context命名空间才能使用这个标签
beans-properties.xmldb.properties都存放在src根目录下
使用外部属性时需要像JSTL那样使用${}来引用属性

<?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"
	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.1.xsd">
	<!-- 导入属性文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	<!-- 导入外部化属性文件的属性 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		p:user="${user}" p:password="${password}" p:driverClass="${driverclass}"
		p:jdbcUrl="${jdbcurl}"></bean>

</beans>

###4.测试是否连接成功
这里写图片描述

**(连接成功)**

猜你喜欢

转载自blog.csdn.net/qq_33596978/article/details/81165103