天天看點

Spring從菜鳥到高手(三)依賴注入

Spring中有一個技術叫做依賴注入,而依賴注入又分為【構造函數】注入和【Set】注入,前面我們都看到了依賴注入的好處和友善之處,大家也許要問【Set】注入和【構造函數】注入有什麼分别呢?

今天我将一個小例子展示給大家這個例子使用了Spring的【構造函數】依賴注入方式,究竟【構造函數】和【Set】這兩種方法哪種好?要看用在什麼地方,如果我們的一個屬性要随着類的執行個體保持不變我們就選擇使用構造方法注入,如果我們的一個屬性變量在這個類的執行個體中會有可能改變,那麼我們就選擇Set注入。

這個例子主要示範的是通過構造函數來實作注入,因為我們這個類的功能是讀取Properties檔案的資訊,以備後面的子產品連接配接資料庫,是以連接配接資料庫的資訊是不能改變的,将它通過構造函數注入是一個很好的  這樣做的好處是 好我們現在就開始

這個類需要導入這幾個包

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

大家注意到這個類的構造方法有一個類型為String的參數負責傳遞進來一個檔案名(相對路徑),通過Class類的getResourceAsStream方法讀取并且傳回一個InputStream類型的對象,

          查找具有給定名稱的資源。

然後java.util.Properties類的load方法将他讀取進屬性清單

 void

          從輸入流中讀取屬性清單(鍵和元素對)。

public class PropertiesConfig {

    private Properties properties = null; 

    public PropertiesConfig(String fileUrl)throws IOException

    {   

        InputStream ips = this.getClass().getResourceAsStream(fileUrl);//通過路徑字元串得到一個流

        if(ips == null)//判斷路徑的正确性,如果錯誤直接抛出異常,不允許向下進行

        {

             throw new IOException("The fileUrl is nullity !"); 

        }

        this.properties = new Properties();

        properties.load(ips);//将得到的流讀取進屬性清單

    }

    public Properties getProperties() {

        return properties;

    public void setProperties(Properties properties) {

        this.properties = properties;

XML配置檔案

<?xml version="1.0" encoding="UTF-8"?>

<beans>

 <bean id="popertiesConfig" class="cn.incast.PropertiesConfig">

  <constructor-arg>

   <value>db.properties</value>         <!--通過構造函數來注入-->

  </constructor-arg>

 </bean>

</beans>

db.properties檔案的内容

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost/itcast

jdbc.user=root

jdba.pass=

可是如果我們的【構造函數】有多個參數我們該怎麼辦呢?

我們可以使用<constructor-arg>的一個屬性【index】

  <constructor-arg  index="1">

還可以使用<constructor-arg>的另一個屬性【type】

  <constructor-arg  type="java.lang.String">

例子1、

<bean id="popertiesConfig" class="cn.incast.PropertiesConfig">

  <constructor-arg index="1">

   <value>db.properties</value>         <!--構造函數參數1-->

   <value>db.properties</value>         <!--構造函數參數2-->

例子2、

  <constructor-arg itypr="java.lang.String">

<!--遇到這種兩個參數都是一個類型,并且無法分辨究竟哪個是第一個參數哪個是第二個參數就需要使用index了-->

  <constructor-arg type="java.lang.String">

----------------------------------------------

以下是通過Set注入的例子很簡單,相信大家,一看就懂

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.logging.Logger;

/*

 * 用于通過propertiesConfig檔案建立連接配接

 * 

 */

public class ConnectionConfig {

 private PropertiesConfig propertiesConfig = null;

 private Logger log = Logger.getLogger("cn.incast.ConnectionConfig");

 public Connection foundConnection()throws IOException,ClassNotFoundException,SQLException

 {

  Properties propts = null;

  Connection cn = null;

  propts = propertiesConfig.getProperties();

  Class.forName(propts.getProperty("jdbc.driver"));

  cn = DriverManager.getConnection(

     propts.getProperty("jdbc.url"),

     propts.getProperty("jdbc.user"),

     propts.getProperty("jdbc.pass"));

  return cn;  

 }

 public void closeConnection(Connection cn)

  if(cn !=null)

  {

   try 

   {

    cn.close();

    cn = null;

   } 

   catch (SQLException e) 

   {log.warning("Connection call on error !");}

  }

 public void closeStatement(Statement stmt)

  if(stmt !=null)

    stmt.close();

    stmt = null;

   {log.warning("Statement call on error !");}

 }public void closeResultSet(ResultSet rs)

  if(rs !=null)

    rs.close();

    rs = null;

   {log.warning("ResultSet call on error !");}

 public PropertiesConfig getPropertiesConfig() {

  return propertiesConfig;

 public void setPropertiesConfig(PropertiesConfig propertiesConfig) {

  this.propertiesConfig = propertiesConfig;

}

這個類是為我下一篇文章作鋪墊的,我的下一篇文章是介紹Spring與資料庫連接配接的一些小的心得,主要使用Spring連接配接資料庫其中用到了JaKarta的BasicDtatSource資料源對象、Sql注入攻擊以及JDBC調用MySql的存儲過程和方法,敬請期待。

本文轉自 tony_action 51CTO部落格,原文連結:http://blog.51cto.com/tonyaction/42041,如需轉載請自行聯系原作者