Spring配置檔案中如何使用外部配置檔案配置資料庫連線
阿新 • • 發佈:2018-11-02
版權宣告:本文為博主原創文章,歡迎指正或者轉載。 https://blog.csdn.net/qq_38663729/article/details/78821258
直接在spring的配置檔案中applicationContext.xml檔案中配置資料庫連線也可以,但是有個問題,需要在url後帶著使用編碼集和指定編碼集,出現瞭如下問題,&這個符號報錯……
既然這樣只能使用外部配置檔案設定一些引數,在spring的配置檔案applicationContext.xml中獲取,然後配置連線資料庫
使用properties配置檔案連線資料庫,在src下新建jdbc.properties檔案,按照自己的資料庫名,使用者名稱密碼更改下面的配置
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/***?useUnicode=true&characterEncoding=utf8
username=****
password=****
在spring的配置檔案applicatiContext.xml中加入(這裡是引入配置檔案)
<!-- 引入jdbc配置檔案 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:jdbc.properties</value> </list> </property> </bean>
更改之前的資料庫配置,名稱和配置檔案中的對應上即可
<!-- 配置資料來源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name="driverClassName" value="${driverClass}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </bean>
整體如下圖: