Spring配置文件支持通过xxx.properties文件的Key获得对应的值。实现该功能是通过
通过${Key}来获得Properties文件对应Key的值
使用Spring读取配置文件必须导入新的命名空间 context。如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.xsd
">
使用Spring创建阿里巴巴 Druid连接池,读取配置文件
拷贝Mysql驱动包和druid连接池jar包到项目中,并加入到项目中
在classpath(src)下创建 db.properites
#批量修改alt+shift+a,使用鼠标多拉,修改完毕以后,alt+shift+a 还原
jdbc.driverName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/gj1?characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
jdbc.maxActive=10
applicationContext.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.3.xsd">
<!-- 读取db.properties配置文件
<context:property-placeholder location="classpath:db.properties"/>
location:文件位置
注意:spring中读取所有配置文件全部要加上:classpath前缀:文件名.properties
-->
<context:property-placeholder location="classpath:db.properties"/>
<!--
使用SpringEL表达式可以读取配置文件的内容
#{}:#{1024*300}。做复杂的计算时,可以用#{}
${}:${xxx.properties配置文件中的key}
druid 连接池的配置的key,不能是username
因为默认读取的是当前操作系统登录账号,不能配置文件中username的值
-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="${jdbc.maxActive}"/>
</bean>
</beans>
测试代码
@Test
public void testName() throws Exception {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取连接池对象
DataSource bean = applicationContext.getBean("dataSource",DataSource.class);
//从连接池中获取连接对象
Connection connection = bean.getConnection();
System.out.println(connection);
}