Spring中配置数据源有多种方式:
方式一:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?characterEncoding=UTF8&serverTimezone=Asia/Shanghai"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> </bean>
方式二(引入外部properties文件):
先准备mysql.properties:
mysql.driver=com.mysql.cj.jdbc.Driver mysql.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF8&serverTimezone=Asia/Shanghai mysql.username=root mysql.password=root然后在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 https://www.springframework.org/schema/context/spring-context.xsd"> <!--引入MySQL的配置信息--> <context:property-placeholder location="mysql.properties"></context:property-placeholder> <!--使用MySQL的配置信息--> <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource"> <property name="driverClass" value="${mysql.driver}"></property> <property name="jdbcUrl" value="${mysql.url}"></property> <property name="user" value="${mysql.username}"></property> <property name="password" value="${mysql.password}"></property> </bean> </beans>