<!-- 配置數據源 -->
<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/eesy?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
需要注意的是url的值在8.0以上必須有useSSL、serverTimezone、allowPublicKeyRetrieval三個屬性的設置,否則在某時刻必會出錯。
Spring配置文件中如何使用外部配置文件配置數據庫連接:
Spring 提供了一個 PropertyPlaceholderConfigurer 的 BeanFactory 后置處理器, 這個處理器允許用戶將 Bean 配置的部分內容外移到屬性文件中.
可以在 Bean 配置文件里使用形式為 ${var} 的變量, PropertyPlaceholderConfigurer 從屬性文件里加載屬性, 並使用這些屬性來替換變量. •Spring 還允許在屬性文件中使用 ${propName},以實現屬性之間的相互引用。 (1)導入屬性文件即剛才新建的db.properties文件,然后value里面的值用${var}引入,var相當於db.properties中的“鍵”, 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: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.0.xsd"> <!-- 導入屬性文件 --> <context:property-placeholder location="jdbcConfig.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 使用外部化屬性文件的屬性 --> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> </beans>
jdbcConfig.properties:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=root
pring 提供了一個 PropertyPlaceholderConfigurer 的 BeanFactory 后置處理器, 這個處理器允許用戶將 Bean 配置的部分內容外移到屬性文件中. 可以在 Bean 配置文件里使用形式為 ${var} 的變量, PropertyPlaceholderConfigurer 從屬性文件里加載屬性, 並使用這些屬性來替換變量.