本文主要讲解如何利用Spring中xml文件配置连接数据源。连接数据库过程中,我们主要是要通过具体的参数,创建一个DataSource的具体对象。然后通过datasource来创建连接。如下所示
// Properties extends Hashtable<Object,Object> 实现了HaseTable接口,可以用来读取一些配置文件
Properties properties = new Properties();
// 不要通过具体路径去读,把配置文件当成有个资源getResourceAsStream
InputStream is = Demo05Druid.class.getClassLoader().getResourceAsStream("jdbc2.properties");
// load 函数的输入是一个流
properties.load(is);
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
for(int i = 0 ; i<10 ; i++){
Connection conn1 = dataSource.getConnection();
System.out.println(i+"-------->"+conn1);
// 注意有close和没有close的区别
// conn1.close();
}
}
那我们也可以利用Spring的xml来注入DataSource 的这些属性。具体配置如下所示:
<!-- 按照bean属性具体取值的方式读入 -->
<!--
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
-->
之前除了直接set DataSource的属性之外,我们还可以通过读取配置文件来设置属性,在xml文件中也可以直接读取配置文件,完成DataSource属性注入。
<?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 https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 以配置文件的形式读入-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 按照bean的方式读入 -->
<!--
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
-->
</beans>
jdbc配置文件内容如下所示:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.username=root
jdbc.password=123456