1. 程式人生 > 程式設計 >Spring引入外部屬性檔案配置資料庫連線的步驟詳解

Spring引入外部屬性檔案配置資料庫連線的步驟詳解

直接配置資料庫的資訊

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:util="http://www.springframework.org/schema/util"
    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/util http://www.springframework.org/schema/util/spring-util.xsd
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

  <!--直接配置連線池-->
  <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/userDb"></property>
    <property name="username" value="root" ></property>
    <property name="password" value="root" ></property>
  </bean>

</beans>

一般不會這樣用,不便於修改,我們看下面的引入外部屬性檔案配置的方法

引入外部屬性檔案配置資料庫連線

1.引入德魯伊連線池jar包

(1)匯入進來一個druid-1.0.9.jar,直接複製貼上到當前目錄就可以了。

在這裡插入圖片描述

(2)引入到當前專案。

在這裡插入圖片描述
在這裡插入圖片描述

2.配置德魯伊連線池

(1)新建一個jdbc.properties檔案,寫資料庫的相關資訊。
jdbc.properties:

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/userDb?characterEncoding=utf8&useUnicode=true&useSSL=false
jdbc.username=root
jdbc.password=root

(2)新建一個配置檔案。

bean6.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:util="http://www.springframework.org/schema/util"
    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/util http://www.springframework.org/schema/util/spring-util.xsd
              http://www.springframework.org/schema/context http://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.driverClass}"></property>
    <property name="url" value="${jdbc.url}" ></property>
    <property name="username" value="${jdbc.username}" ></property>
    <property name ="password" value="${jdbc.password}" ></property>

  </bean>

</beans>

完成以上步驟,就完成了引入外部屬性檔案配置資料庫連線。

到此這篇關於Spring引入外部屬性檔案配置資料庫連線的步驟詳解的文章就介紹到這了,更多相關Spring外部屬性檔案內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!