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
相关文章
相关标签/搜索