spring注入

 IOC容器的對象實例化是經過配置文件來實現的。術語上這叫作注入。注入有兩種形式,採用構造方法注入和採用setter注入。具體的注入形式以下html

**************構造方法方式*******************java

UserManagerImpl類:node

 

[java]  view plain  copy
  1. package com.bjpowernode.spring.manager;  
  2.   
  3. import com.bjpowernode.spring.dao.UserDao;  
  4.   
  5. public class UserManagerImpl implements UserManager {  
  6.       
  7.     private UserDao userDao;  
  8.       
  9.     public UserManagerImpl(UserDao userDao) {  
  10.         this.userDao = userDao;  
  11.     }  
  12.   
  13.   
  14. }  

 

配置文件代碼:程序員

 

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  7.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd  
  8.            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">  
  9.   
  10.     <bean id="userDao4Mysql" class="com.bjpowernode.spring.dao.UserDao4MySqlImpl" />  
  11.   
  12.     <bean id="userManager" class="com.bjpowernode.spring.manager.UserManagerImpl">  
  13.         <constructor-arg ref="userDao4Mysql" />  
  14.     </bean>  
  15. </beans>  

 

****************setter方式*****************web

UserManagerImpl類:spring

 

[java]  view plain  copy
  1. package com.bjpowernode.spring.manager;  
  2.   
  3. import com.bjpowernode.spring.dao.UserDao;  
  4.   
  5. public class UserManagerImpl implements UserManager {  
  6.       
  7.     private UserDao userDao;  
  8.   
  9.     public void setUserDao(UserDao userDao) {  
  10.         this.userDao = userDao;  
  11.     }  
  12.   
  13. }  

 

配置文件代碼:sql

 

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  7.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd  
  8.            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">  
  9.   
  10.     <bean id="userDao4Mysql" class="com.bjpowernode.spring.dao.UserDao4MySqlImpl" />  
  11.   
  12.     <bean id="userManager" class="com.bjpowernode.spring.manager.UserManagerImpl">  
  13. <!--         <constructor-arg ref="userDao4Mysql" /> -->  
  14.         <property name="userDao" ref="userDao4Mysql" />  
  15.     </bean>  
  16. </beans>  

 

比較:app

1.構造方法:編輯器

對於依賴關係無須變化的Bean,構造注入更有用處;由於沒有setter方法,全部的依賴關係所有在構造器內設定,所以,不用擔憂後續代碼對依賴關係的破壞。依賴關係只能在構造器中設定,則只有組件的建立者才能改變組件的依賴關係。對組件的調用者而言,組件內部的依賴關係徹底透明,更符合高內聚的原則。ide

構造注入能夠在構造器中決定依賴關係的注入順序。

2setter方法:

與傳統的JavaBean的寫法更類似,程序員更容易理解、接受,經過setter方式設定依賴關係顯得更加直觀、明顯;對於複雜的依賴關係,若是採用構造注入,會致使構造器過於臃腫,難以閱讀。Spring在建立Bean實例時,須要同時實例化其依賴的所有實例,於是致使死你功能降低。而使用設置注入,則避免這下問題;尤爲在某些屬性可選的狀況下,多參數的構造器更加笨拙。

【屬性編輯器】

Spring內置了一些屬性編輯器,能夠將一些普一般用的屬性注入,將Spring配置文件中的String類型轉換成相應的Java對象。例如一個類裏面的一個整型屬性,在配置文件中咱們是經過String類型的數字直接進行配置便可。以下示例:

Bean1類:

 

[java]  view plain  copy
  1. package com.bjpowernode.spring;  
  2.   
  3. import java.util.Date;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import java.util.Set;  
  7.   
  8. public class Bean1 {  
  9.   
  10.     private String strValue;  
  11.       
  12.     private int intValue;  
  13.       
  14.     private List listValue;  
  15.       
  16.     private Set setValue;  
  17.       
  18.     private String[] arrayValue;  
  19.       
  20.     private Map mapValue;  
  21.       
  22.     private Date dateValue;  
  23.   
  24.     //get和set略  
  25.       
  26.   
  27. }  

 

配置文件:

 

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  7.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd  
  8.            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"  
  9.     default-lazy-init="true">  
  10.     <bean id="bean1" class="com.bjpowernode.spring.Bean1">  
  11.         <property name="strValue" value="Hello_Spring" />  
  12.   
  13.         <!-- <property name="intValue" value="123"/> -->  
  14.         <property name="intValue">  
  15.             <value>123</value>  
  16.         </property>  
  17.   
  18.         <property name="listValue">  
  19.             <list>  
  20.                 <value>list1</value>  
  21.                 <value>list2</value>  
  22.             </list>  
  23.         </property>  
  24.         <property name="setValue">  
  25.             <set>  
  26.                 <value>set1</value>  
  27.                 <value>set2</value>  
  28.             </set>  
  29.         </property>  
  30.         <property name="arrayValue">  
  31.             <list>  
  32.                 <value>array1</value>  
  33.                 <value>array2</value>  
  34.             </list>  
  35.         </property>  
  36.         <property name="mapValue">  
  37.             <map>  
  38.                 <entry key="k1" value="v1" />  
  39.                 <entry key="k2" value="v2" />  
  40.             </map>  
  41.         </property>  
  42.     </bean>  
  43.   
  44. </beans>  

 

測試方法:

 

[java]  view plain  copy
  1. package test;  
  2.   
  3. import org.springframework.beans.factory.BeanFactory;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. import com.bjpowernode.spring.Bean1;  
  7.   
  8. import junit.framework.TestCase;  
  9.   
  10. public class InjectionTest extends TestCase {  
  11.   
  12.     private BeanFactory factory;  
  13.   
  14.     @Override  
  15.     protected void setUp() throws Exception {  
  16.         String[] configLocations = new String[] {  
  17.                 "applicationContext-beans.xml"};  
  18.   
  19.         factory = new ClassPathXmlApplicationContext(configLocations);  
  20.     }  
  21.   
  22.     @Override  
  23.     protected void tearDown() throws Exception {  
  24.   
  25.     }  
  26.   
  27.     public void testInjection1() {  
  28.         Bean1 bean1 = (Bean1) factory.getBean("bean1");  
  29.         System.out.println("bean1.strValue=" + bean1.getStrValue());  
  30.         System.out.println("bean1.intValue=" + bean1.getIntValue());  
  31.         System.out.println("bean1.listValue=" + bean1.getListValue());  
  32.         System.out.println("bean1.setValue=" + bean1.getSetValue());  
  33.         System.out.println("bean1.arrayValue=" + bean1.getArrayValue());  
  34.         System.out.println("bean1.mapValue=" + bean1.getMapValue());  
  35.         System.out.println("bean1.dateValue=" + bean1.getDateValue());  
  36.     }  
  37.   
  38. }  

 

【自定義屬性編輯器】

Spring具備多個自定義編輯器,它們可以自動把注入的String值轉化爲更復雜的類型。例如Date類型,若是直接按照上面實例的方式進行配置,就會報錯以下:

org.springframework.beans.factory.BeanCreationException:Error creating bean with name 'bean' defined in class path resource[applicationContext.xml]: Initialization of bean failed; nested exception isorg.springframework.beans.TypeMismatchException: Failed to convert propertyvalue of type [java.lang.String] to required type [java.util.Date] for property'date';

由於Spring沒有內置Date的屬性編輯器,須要咱們本身建立。建立過程:

1.編寫UtilDatePropertyEditor類,繼承PropertyEditorSupport,覆蓋setAsText()方法,其中text參數就是配置文件中的值。咱們的任務就是把text轉換成date類型的值。

 

[java]  view plain  copy
  1. package com.bjpowernode.spring;  
  2.   
  3. import java.beans.PropertyEditorSupport;  
  4. import java.text.ParseException;  
  5. import java.text.SimpleDateFormat;  
  6. import java.util.Date;  
  7.   
  8. /** 
  9.  * java.util.Date屬性編輯器 
  10.  * @author Administrator 
  11.  * 
  12.  */  
  13. public class UtilDatePropertyEditor extends PropertyEditorSupport {  
  14.   
  15.     private String pattern;  
  16.       
  17.     @Override  
  18.     public void setAsText(String text) throws IllegalArgumentException {  
  19.         System.out.println("---UtilDatePropertyEditor.setAsText()--->" + text);  
  20.         try {  
  21.             Date date = new SimpleDateFormat(pattern).parse(text);  
  22.             this.setValue(date);  
  23.         } catch (ParseException e) {  
  24.             // TODO Auto-generated catch block  
  25.             e.printStackTrace();  
  26.             throw new IllegalArgumentException(text);  
  27.         }  
  28.     }  
  29.   
  30.     public void setPattern(String pattern) {  
  31.         this.pattern = pattern;  
  32.     }  
  33.   
  34.       
  35. }  

 

2.將自定義的屬性編輯器注入到spring中,爲了方便管理咱們再新建一個配置文件applicationContext-editor.xml(測試時記得將該配置文件一同加載便可)

 

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.          xmlns:aop="http://www.springframework.org/schema/aop"  
  6.          xmlns:tx="http://www.springframework.org/schema/tx"  
  7.          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  8.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd  
  9.            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">  
  10.     <bean id="customEditors" class="org.springframework.beans.factory.config.CustomEditorConfigurer">  
  11.         <property name="customEditors">  
  12.             <map>  
  13.                 <entry key="java.util.Date">  
  14.                     <bean class="com.bjpowernode.spring.UtilDatePropertyEditor">  
  15.                         <property name="pattern" value="yyyy年MM月dd日"/>  
  16.                     </bean>  
  17.                 </entry>  
  18.             </map>  
  19.         </property>  
  20.     </bean>  
  21. </beans
相關文章
相關標籤/搜索