spring六種種依賴注入方式

 

日常的java開發中,程序員在某個類中須要依賴其它類的方法,則一般是new一個依賴類再調用類實例的方法,這種開發存在的問題是new的類實例很差統一管理,spring提出了依賴注入的思想,即依賴類不禁程序員實例化,而是經過spring容器幫咱們new指定實例而且將實例注入到須要該對象的類中。依賴注入的另外一種說法是「控制反轉」,通俗的理解是:日常咱們new一個實例,這個實例的控制權是咱們程序員,而控制反轉是指new實例工做不禁咱們程序員來作而是交給spring容器來作。
 
spring有多種依賴注入的形式,下面僅介紹spring經過xml進行IOC配置的方式:
  • Set注入
這是最簡單的注入方式,假設有一個SpringAction,類中須要實例化一個SpringDao對象,那麼就能夠定義一個private的SpringDao成員變量,而後建立SpringDao的set方法(這是ioc的注入入口):
Java代碼   收藏代碼
  1. package com.bless.springdemo.action;  
  2. public class SpringAction {  
  3.         //注入對象springDao  
  4.     private SpringDao springDao;  
  5.         //必定要寫被注入對象的set方法  
  6.         public void setSpringDao(SpringDao springDao) {  
  7.         this.springDao = springDao;  
  8.     }  
  9.   
  10.         public void ok(){  
  11.         springDao.ok();  
  12.     }  
  13. }  
 
隨後編寫spring的xml文件,<bean>中的name屬性是class屬性的一個別名,class屬性指類的全名,由於在SpringAction中有一個公共屬性Springdao,因此要在<bean>標籤中建立一個<property>標籤指定SpringDao。<property>標籤中的name就是SpringAction類中的SpringDao屬性名,ref指下面<bean name="springDao"...>,這樣實際上是spring將SpringDaoImpl對象實例化而且調用SpringAction的setSpringDao方法將SpringDao注入:
Java代碼   收藏代碼
  1. <!--配置bean,配置後該類由spring管理-->  
  2.     <bean name="springAction" class="com.bless.springdemo.action.SpringAction">  
  3.         <!--(1)依賴注入,配置當前類中相應的屬性-->  
  4.         <property name="springDao" ref="springDao"></property>  
  5.     </bean>  
  6. <bean name="springDao" class="com.bless.springdemo.dao.impl.SpringDaoImpl"></bean>  
  
 
  • 構造器注入
這種方式的注入是指帶有參數的構造函數注入,看下面的例子,我建立了兩個成員變量SpringDao和User,可是並未設置對象的set方法,因此就不能支持第一種注入方式,這裏的注入方式是在SpringAction的構造函數中注入,也就是說在建立SpringAction對象時要將SpringDao和User兩個參數值傳進來:
Java代碼   收藏代碼
  1. public class SpringAction {  
  2.     //注入對象springDao  
  3.     private SpringDao springDao;  
  4.     private User user;  
  5.       
  6.     public SpringAction(SpringDao springDao,User user){  
  7.         this.springDao = springDao;  
  8.         this.user = user;  
  9.         System.out.println("構造方法調用springDao和user");  
  10.     }  
  11.           
  12.         public void save(){  
  13.         user.setName("卡卡");  
  14.         springDao.save(user);  
  15.     }  
  16. }  
 
在XML文件中一樣不用<property>的形式,而是使用<constructor-arg>標籤,ref屬性一樣指向其它<bean>標籤的name屬性:
Xml代碼   收藏代碼
  1. <!--配置bean,配置後該類由spring管理-->  
  2.     <bean name="springAction" class="com.bless.springdemo.action.SpringAction">  
  3.         <!--(2)建立構造器注入,若是主類有帶參的構造方法則需添加此配置-->  
  4.         <constructor-arg ref="springDao"></constructor-arg>  
  5.         <constructor-arg ref="user"></constructor-arg>  
  6.     </bean>  
  7.         <bean name="springDao" class="com.bless.springdemo.dao.impl.SpringDaoImpl"></bean>  
  8.          <bean name="user" class="com.bless.springdemo.vo.User"></bean>  
  解決構造方法參數的不肯定性,你可能會遇到構造方法傳入的兩參數都是同類型的,爲了分清哪一個該賦對應值,則須要進行一些小處理:
下面是設置index,就是參數位置:
Xml代碼   收藏代碼
  1. <bean name="springAction" class="com.bless.springdemo.action.SpringAction">  
  2.         <constructor-arg index="0" ref="springDao"></constructor-arg>  
  3.         <constructor-arg index="1" ref="user"></constructor-arg>  
  4.     </bean>  
  另外一種是設置參數類型:
Xml代碼   收藏代碼
  1. <constructor-arg type="java.lang.String" ref=""/>  
 
  • 靜態工廠的方法注入
靜態工廠顧名思義,就是經過調用靜態工廠的方法來獲取本身須要的對象,爲了讓spring管理全部對象,咱們不能直接經過"工程類.靜態方法()"來獲取對象,而是依然經過spring注入的形式獲取:
Java代碼   收藏代碼
  1. package com.bless.springdemo.factory;  
  2.   
  3. import com.bless.springdemo.dao.FactoryDao;  
  4. import com.bless.springdemo.dao.impl.FactoryDaoImpl;  
  5. import com.bless.springdemo.dao.impl.StaticFacotryDaoImpl;  
  6.   
  7. public class DaoFactory {  
  8.     //靜態工廠  
  9.     public static final FactoryDao getStaticFactoryDaoImpl(){  
  10.         return new StaticFacotryDaoImpl();  
  11.     }  
  12. }  
 
一樣看關鍵類,這裏我須要注入一個FactoryDao對象,這裏看起來跟第一種注入如出一轍,可是看隨後的xml會發現有很大差異:
Java代碼   收藏代碼
  1.  public class SpringAction {  
  2.         //注入對象  
  3.     private FactoryDao staticFactoryDao;  
  4.       
  5.     public void staticFactoryOk(){  
  6.         staticFactoryDao.saveFactory();  
  7.     }  
  8.     //注入對象的set方法  
  9.     public void setStaticFactoryDao(FactoryDao staticFactoryDao) {  
  10.         this.staticFactoryDao = staticFactoryDao;  
  11.     }  
  12. }  
 
Spring的IOC配置文件,注意看<bean name="staticFactoryDao">指向的class並非FactoryDao的實現類,而是指向靜態工廠DaoFactory,而且配置 factory-method="getStaticFactoryDaoImpl"指定調用哪一個工廠方法:
Xml代碼   收藏代碼
  1. <!--配置bean,配置後該類由spring管理-->  
  2.     <bean name="springAction" class="com.bless.springdemo.action.SpringAction" >  
  3.         <!--(3)使用靜態工廠的方法注入對象,對應下面的配置文件(3)-->  
  4.         <property name="staticFactoryDao" ref="staticFactoryDao"></property>  
  5.                 </property>  
  6.     </bean>  
  7.     <!--(3)此處獲取對象的方式是從工廠類中獲取靜態方法-->  
  8.     <bean name="staticFactoryDao" class="com.bless.springdemo.factory.DaoFactory" factory-method="getStaticFactoryDaoImpl"></bean>  
  9.       
 
 
 
  • 實例工廠的方法注入
實例工廠的意思是獲取對象實例的方法不是靜態的,因此你須要首先new工廠類,再調用普通的實例方法:
Java代碼   收藏代碼
  1. public class DaoFactory {  
  2.     //實例工廠  
  3.     public FactoryDao getFactoryDaoImpl(){  
  4.         return new FactoryDaoImpl();  
  5.     }  
  6. }  
那麼下面這個類沒什麼說的,跟前面也很類似,可是咱們須要經過實例工廠類建立FactoryDao對象:
Java代碼   收藏代碼
  1. public class SpringAction {  
  2.     //注入對象  
  3.     private FactoryDao factoryDao;  
  4.       
  5.     public void factoryOk(){  
  6.         factoryDao.saveFactory();  
  7.     }  
  8.   
  9.     public void setFactoryDao(FactoryDao factoryDao) {  
  10.         this.factoryDao = factoryDao;  
  11.     }  
  12. }  
 
最後看spring配置文件:
Xml代碼   收藏代碼
  1. <!--配置bean,配置後該類由spring管理-->  
  2.     <bean name="springAction" class="com.bless.springdemo.action.SpringAction">  
  3.         <!--(4)使用實例工廠的方法注入對象,對應下面的配置文件(4)-->  
  4.         <property name="factoryDao" ref="factoryDao"></property>  
  5.     </bean>  
  6.       
  7.     <!--(4)此處獲取對象的方式是從工廠類中獲取實例方法-->  
  8.     <bean name="daoFactory" class="com.bless.springdemo.factory.DaoFactory"></bean>  
  9.     <bean name="factoryDao" factory-bean="daoFactory" factory-method="getFactoryDaoImpl"></bean>  
 
 
  • 總結
Spring IOC注入方式用得最多的是(1)(2)種,多謝多練就會很是熟練。
        另外注意:經過Spring建立的對象默認是單例的,若是須要建立多實例對象能夠在<bean>標籤後面添加一個屬性:
Java代碼   收藏代碼
  1. <bean name="..." class="..." scope="prototype">  
 

 

Java代碼   收藏代碼
  1. Spring的依賴注入(接口注入)  
  2. 2009-11-26 10:06 148人閱讀 評論(0) 收藏 舉報  
  3.   這篇文章來談談《Spring Framework 開發參考手冊》的3.3.3.1小節中的Lookup方法注入。  
  4.    
  5.   仔細看看文檔,這種方法主要是用在Singleton的Object中使用非Singleton的Bean時,經過lookup-method的  
Java代碼   收藏代碼
  1. 那個方法來取得非Singleton的Bean。通常用的很少,在用這種定義以前最好想明白你的需求。  
  2.    
  3.    
  4. · 先創建一個包:javamxj.spring.basic.lookup ,而後把如下5個文件放在這個包下。  
  5.    
  6. Hello.java.   
  7. package javamxj.spring.basic.lookup;  
  8. public interface Hello {  
  9.     public Random getRandom();  
  10.     public abstract Random createRandom();  
  11. }  
  12.    
  13.    
  14. Random.java  
  15.    
  16. package javamxj.spring.basic.lookup;  
  17. public class Random {  
  18.     private int i = (int) (100 * Math.random());  
  19.     public void printRandom() {  
  20.         System.out.println("輸出隨機整數:  " + i);  
  21.     }  
  22. }  
  23.    
  24.    
  25. HelloAbstract.java   
  26. package javamxj.spring.basic.lookup;  
  27. public abstract class HelloAbstract implements Hello {  
  28.     private Random random;  
  29.     public Random getRandom() {  
  30.         return random;  
  31.     }  
  32.     public void setRandom(Random random) {  
  33.         this.random = random;  
  34.     }  
  35.     public abstract Random createRandom();  
  36. }  
  37.    
  38.    
  39. beans.xml   
  40. <?xml version="1.0" encoding="GBK"?>  
  41. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
  42. <beans>  
  43.     <bean id="ran" class="javamxj.spring.basic.lookup.Random" singleton="false"/>  
  44.       
  45.     <bean id="hello" class="javamxj.spring.basic.lookup.HelloAbstract">  
  46.         <lookup-method name="createRandom" bean="ran"/>  
  47.         <property name="random">  
  48.             <ref local="ran"/>  
  49.         </property>  
  50.     </bean>  
  51.       
  52. </beans>  
  53.    
  54.    
  55. Main.java  
  56.    
  57. package javamxj.spring.basic.lookup;  
  58. import org.springframework.beans.factory.BeanFactory;  
  59. import org.springframework.beans.factory.xml.XmlBeanFactory;  
  60. import org.springframework.core.io.ClassPathResource;  
  61. import org.springframework.core.io.Resource;  
  62. public class Main {  
  63.     public static void main(String[] args) {  
  64.         Resource res = new ClassPathResource( "javamxj/spring/basic/lookup/beans.xml");  
  65.         BeanFactory ft = new XmlBeanFactory(res);  
  66.         Hello h = (Hello) ft.getBean("hello");  
  67.         Random r1 = h.getRandom();  
  68.         Random r2 = h.getRandom();  
  69.         System.out.println("沒有采用Lookup方法注入:");  
  70.         System.out.println("Random 的兩個實例指向同一個引用:" + (r1 == r2));  
  71.         r1.printRandom();  
  72.         r2.printRandom();  
  73.         Random r3 = h.createRandom();  
  74.         Random r4 = h.createRandom();  
  75.         System.out.println("/n採用Lookup方法注入:");  
  76.         System.out.println("Random 的兩個實例指向同一個引用:" + (r3 == r4));  
  77.         r3.printRandom();  
  78.         r4.printRandom();  
  79.     }  
  80. }    
  81.    
  82.    
  83. 簡單說明一下:  
  84.    
  85. · Hello是一個接口類,實現面向接口編程。  
  86.    
  87. · Random類用來輸出隨機整數。  
  88.    
  89. · HelloAbstract是一個抽象類,包含了一個屬性:random,還包含一個抽象方法createRandom(),若是這個方法不是抽象的,spring會重寫已有的實現。  
  90.    
  91. · beans.xml中定義了兩個bean,ran指向Rondom類,注意它不是singleton的;hello指向HelloAbstract類,其中的random屬性指向ran,createRandom方法也指向ran。  
  92.    
  93. · 在Main類中,Hello類分別利用getRandom()和createRandom()方法來調用Random類。  
  94.    
  95. · 此次須要將 spring-framework主目錄/lib/cglib 目錄中的cglib-nodep-2.1_2.jar加入到項目的 Libraries中,使用其中的動態代理。  
  96.    
  97.    
  98. 運行結果:  
  99.    
  100. 沒有采用Lookup方法注入:  
  101. Random 的兩個實例指向同一個引用:true  
  102. 輸出隨機整數:  98  
  103. 輸出隨機整數:  98  
  104.    
  105. 採用Lookup方法注入:  
  106. Random 的兩個實例指向同一個引用:false  
  107. 輸出隨機整數:  51  
  108. 輸出隨機整數:  26  
  109.   
  110. 本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/javamxj/archive/2005/08/17/456600.aspx  

 個人理解:接口注入實際上是,經過配置Spring的lookup-method,及返回值 ,能夠返回接口中方法的返回值而不須要實現接口中的抽象方法

註解注入顧名思義就是經過註解來實現注入,Spring和注入相關的常見註解有Autowired、Resource、Qualifier、Service、Controller、Repository、Component。java

  • Autowired是自動注入,自動從spring的上下文找到合適的bean來注入
  • Resource用來指定名稱注入
  • Qualifier和Autowired配合使用,指定bean的名稱
  • Service,Controller,Repository分別標記類是Service層類,Controller層類,數據存儲層的類,spring掃描註解配置時,會標記這些類要生成bean。
  • Component是一種泛指,標記類是組件,spring掃描註解配置時,會標記這些類要生成bean。

上面的Autowired和Resource是用來修飾字段,構造函數,或者設置方法,並作注入的。而Service,Controller,Repository,Component則是用來修飾類,標記這些類要生成bean。node

下面咱們經過實例項目來看下spring註解注入的使用。mysql

首先新建一個maven項目,並在pom中添加spring相關的依賴,若是不知道添加那些依賴,請參照上一篇文章。程序員

而後新建CarDao類,給它添加@Repository註解,以下代碼:spring

package cn.outofmemory.helloannotation; import org.springframework.stereotype.Repository; @Repository public class CarDao { public void insertCar(String car) { String insertMsg = String.format("inserting car %s", car); System.out.println(insertMsg); } }

新建CarService類,並給該類標註@Service註解,在這個類中定義CarDao的字段,並經過Autowired來修飾此字段,這樣上面定義的CarDao類的實例就會自動注入到CarService的實例中了。sql

package cn.outofmemory.helloannotation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CarService { @Autowired private CarDao carDao; public void addCar(String car) { this.carDao.insertCar(car); } }

注意:Autowired註解有一個能夠爲空的屬性required,能夠用來指定字段是不是必須的,若是是必需的,則在找不到合適的實例注入時會拋出異常。編程

下面咱們在App.java中使用上面測試下註解注入:app

package cn.outofmemory.helloannotation; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Hello world! * */ public class App { public static void main( String[] args ) { ApplicationContext appContext = new AnnotationConfigApplicationContext("cn.outofmemory.helloannotation"); CarService service = appContext.getBean(CarService.class); service.addCar("寶馬"); } }

在上面的main方法中首先咱們初始化了appContext,他是AnnotationConfigApplicationContext,它的構造函數接受一個package的名稱,來限定要掃描的package。而後就能夠經過appContext的getBean方法得到CarService的實例了。less

上面的例子很是簡單,單純的使用AnnotationConfigApplicationContext就能夠了,可是在實際項目中狀況每每沒有這麼簡單,仍是須要spring配置文件的。在spring配置文件中也能夠經過下面的配置讓spring自動掃描註解配置。dom

    <!-- bean annotation driven --> <context:annotation-config /> <context:component-scan base-package="cn.outofmemory.helloannotation" > </context:component-scan>

下面咱們看下混合使用spring配置和註解的例子,首先在項目中添加source folder,src/main/resources,並添加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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!-- bean annotation driven --> <context:annotation-config /> <context:component-scan base-package="cn.outofmemory.helloannotation" > </context:component-scan> <bean id="sqliteCarDao" class="cn.outofmemory.helloannotation.CarDao" > <constructor-arg name="driver" value="sqlite"/> </bean> </beans>

在上面的配置文件中,咱們經過context:annotation-config和context:component-sacn節點來指定要掃描註解注入,而後又定義了一個id爲sqliteCarDao的bean,它的構造函數的driver值爲sqlite。

咱們修改下App.java使用xml配置文件,再運行下App看下會怎樣。

package cn.outofmemory.helloannotation; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Hello world! * */ public class App { public static void main( String[] args ) { //ApplicationContext appContext = new AnnotationConfigApplicationContext("cn.outofmemory.helloannotation"); ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring.xml"); CarService service = appContext.getBean(CarService.class); service.addCar("寶馬"); } }

運行程序發現輸出爲:inserting car 寶馬 into mysql,顯然CarService自動注入的CarDao使用了默認構造函數構造的實例。是否能夠經過註解指定使用spring.xml中配置的sqliteCarDao呢?

咱們能夠修改下CarService類,經過Qualifier註解來指定要使用的bean的名字。

以下,在指定Autowired註解時,同時指定Qualifier註解指定bean的名字

    @Autowired @Qualifier("sqliteCarDao") private CarDao carDao;

從新運行下App.java 此次輸出的是inserting car 寶馬 into sqlite,此次使用了spring.xml中配置的bean了。

在文中開頭咱們還提到了Resouce註解,這個註解能夠指定名字注入,咱們再次修改下CarService類:

    @Resource(name="sqliteCarDao") private CarDao carDao;

javax.annotation.Resource註解實現的效果和@Autowired+@Qualifier的效果是同樣的。

相關文章
相關標籤/搜索