Spring中applicationContext.xml配置文件中數據庫數據源配置

           【0】 前言Java Web開發的無論哪種框架都離不開各種xml配置,Spring配置文件是用於指導Spring工廠進行Bean生產、依賴關係注入(裝配)及Bean實例分發的“圖紙”。Java EE程序員必須學會並靈活應用這份“圖紙”準確地表達自己的“生產意圖”。Spring配置文件是一個或多個標準的XML文檔,ApplicationContext.xml是Spring的默認配置文件,當容器啓動時找不到指定的配置文檔時,將會嘗試加載這個默認的配置文件。本文着重講數據庫數據源配置。
       【1】作用:使用ApplicationContext,你可以讓系統加載你的bean(例如,在Servlet容器初始化ContextLoaderServlet時,通過ContextLoader類加載Spring Framework),而不是使用編碼方式來加載。 ApplicationContext接口是context包的基礎,位於org.springframework.context包裏,提供了BeanFactory的所有功能。除此之外, ApplicationContext爲了支持Framework的工作方式,提供了以下的功能:
 
       a.MessageSource,提供了語言信息的國際化支持
        b.提供資源(如URL和文件系統)的訪問支持
        c.爲實現了ApplicationListener接口的bean提供了事件傳播支持
        d.爲不同的應用環境提供不同的context,例如支持web應用的XmlWebApplicationContext類
      【2】數據源配置:

<!-- 頭文件,主要注意一下編碼 -->

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN""http://www.springframework.org/dtd/spring-beans.dtd">  
  3. <beans>  

<!-- 建立數據源 -->

  1. <bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource">  

  <!-- 數據庫驅動,我這裏使用的是Mysql數據庫 -->

  1. <propertyname propertyname="driverClassName">  
  2.     <value>com.mysql.jdbc.Driver</value>  
  3.    </property>  

  <!-- 數據庫地址,這裏也要注意一下編碼,不然亂碼可是很鬱悶的哦! -->

  1. <property name="url">  
  2.     <value>  
  3.       jdbc:mysql://localhost:3306/tie?useUnicode=true&characterEncoding=utf-8  
  4.    </value>  
  5.    </property>  

  <!-- 數據庫的用戶名 -->

  1. <property name="username">  
  2.     <value>root</value>  
  3.    </property>  

  <!-- 數據庫的密碼 --> 

  1. <property name="password">  
  2.     <value>123</value>  
  3.    </property>  
  4. </bean>  

<!-- 把數據源注入給Session工廠 -->

  1. <bean id="sessionFactory"  
  2.   class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  3.    <property name="dataSource">  
  4.     <ref bean="dataSource" />  
  5.    </property>  

  <!-- 配置映射文件 --> 

  1. <property name="mappingResources">  
  2.     <list>  
  3.      <value>com/alonely/vo/User.hbm.xml</value>  
  4.     </list>  
  5.    </property>  
  6. </bean> 
   上面是一個MySQL的例子,下面我將其他的數據庫彙總如下:

(1) Oracle
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.101)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=orcl)(SERVER=DEDICATED)))" />
<property name="username" value="rootl" />
<property name="password" value="1234" />
</bean>
   (2)DB2
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.ibm.db2.jdbc.app.DB2Driver" />
<property name="url" value="jdbc:db2:thin:@localhost:5000/testDB" />
<property name="username" value="rootl" />
<property name="password" value="1234" />
</bean>
  (3)SQL Server
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.microsoft.jdbc.sqlserver.SQLServerDriver" />
<property name="url" value="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName = testDB" />
<property name="username" value="rootl" />
<property name="password" value="1234" />
</bean>
   
 org.apache.commons.dbcp.BasicDataSource 需要commons-pool.jar,commons-dbcp-1.2.2.jar,commons-collections-3.2.jar三個JAR包,但是這種模式不能動態修改數據庫,下面將介紹動態修改數據庫鏈接。

【3】動態修改數據庫鏈接(此沒經過具體測試,轉自點擊打開鏈接

需要訪問多個數據庫,而且需要在服務器運行不重新啓動的情況下,動態的修改spring中配置的數據源datasource,spring的配置文件是在容器啓動的時候就加載到內存中的,如果手動改了application.xml,我們必須要重新啓動服務器配置文件纔會生效。而在spring中提供了一個類WebApplicationContext,這個類可以讓你獲得一些bean,可以修改內存中的信息,通過這個類來實現的。下面是具體的代碼。 

package com.southdigital.hospital; 
import java.io.IOException; 
import javax.servlet.ServletContext; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import org.springframework.web.context.WebApplicationContext; 
import org.springframework.web.context.support.WebApplicationContextUtils; 
import com.mchange.v2.c3p0.ComboPooledDataSource; 

public class ChangeSpringConfig extends HttpServlet 
{ 
private String ipAddress = "127.0.0.1"; 
/** 
* The doGet method of the servlet. <br> 
* 
* This method is called when a form has its tag value method equals to get. 
* 
* @param request the request send by the client to the server 
* @param response the response send by the server to the client 
* @throws ServletException if an error occurred 
* @throws IOException if an error occurred 
*/ 

public void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException 
{ 
doPost(request, response); 
} 

/** 
* The doPost method of the servlet. <br> 
* 
* This method is called when a form has its tag value method equals to post. 
* 
* @param request the request send by the client to the server 
* @param response the response send by the server to the client 
* @throws ServletException if an error occurred 
* @throws IOException if an error occurred 
*/ 
public void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException 
{ 
//先取得servleContext對象,提供給spring的WebApplicationUtils來動態修改applicationContext.xml 

ipAddress = request.getParameter("ipAddress"); 
System.out.println(ipAddress); 

ServletContext servletContext = this.getServletContext(); 
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); 
    ComboPooledDataSource cpds = (ComboPooledDataSource) applicationContext.getBean("dataSource"); 
    cpds.setJdbcUrl("jdbc:mysql://"+ipAddress+":3306/ssh"); 
} 
} 
注意:通過這種方法修改applicationContext.xml文件的時候用c3p0,而不可以用dbcp,dbcp不支持動態修改讀取到內存裏面的數據。

【4】Spring與Hibernate通過applicationContext.xml關聯

配置Spring,使它能管理Hibernate。其實,只要在Spring的配置文件(我們這裏是applicationContext.xml中配置一個叫做sessionFactorybeanSpring就可以和Hibernate聯繫起來了。
<bean id="sessionFactory" class="org.springframework.orm.hibernate.Local SessionFactoryBean">
    <property name="configLocation">
    <value>com/ascent/bean/hibernate.cfg.xml</value>
    </property>
</bean>
樣,SpringHibernate的第一步整合就完成了,現在到了關鍵的地方—如何讓SpringHibernate雙劍合璧來實現業務邏輯?
還是在applicationContext.xml文件中先做一個配置。
<bean id="transactionManager" class="org.springframework.orm.hibernate. HibernateTransactionManager">
    <property name="sessionFactory">
      <ref local="sessionFactory"/>
    </property>
  </bean>
在上面你大概可以感覺到Spring給我們帶來的好處了,SpringIoC模式可以統一管理各層,而又使各層鬆散耦合在一起,使各層之間實現最大的解耦性,這也是Web架構一向的追求。
                        (2)http://blog.csdn.net/snn1410/article/details/7846582
                        (3)http://blog.csdn.net/lhzjj/article/details/27403463
                        (4)http://blog.csdn.net/foxhlc/article/details/8789416

    
發佈了47 篇原創文章 · 獲贊 44 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章