mybatis配置檔案匯入外部properties檔案
阿新 • • 發佈:2018-12-13
1. 建立一個db.properties檔案
2.在db.properties檔案中寫入相關配置。例如,資料庫的配置如下:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/newhelp
jdbc.username=root
jdbc.password=123
注意:在定義這些變數的時候,儘量避免一些系統變數,會出錯的。比如username,這個代表作業系統的使用者名稱。
3.在配置Spring-mybatis的Bean檔案時,比如引入頭宣告,如下所示:
<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.xsd">
4.Bean配置檔案加入:
<!-- 匯入db配置 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:spring/db.properties" />
5.使用我們的配置好的變數,連線資料庫:
<!-- Druid --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean>