spring的自动装配

bean标签的autowire属性:

1.no           是默认值,默认不自动装配。

 

一般的配置如下

 <bean id="customersServiceImpl" class="cn.csdn.hr.service.CustomersServiceImpl">

       <property name="customersDao">

           <ref bean="customersDao"/>

       </property>

       <property name="baseDao">

           <ref bean="baseDao"/>

       </property>

    </bean>

    <bean id="customersDao" class="cn.csdn.hr.dao.CustomersDaoImpl"/>

    <bean id="baseDao" class="cn.csdn.hr.dao.BaseHibernateDaoImpl"/>

 

 

2.byName   根据属性名来自动装配。查找与属性名一致的bean,并将它与属性自动装配

      例如:有属性名为student则找id为student的bean,并装配给student属性

 属性名要和参考的bean的id值完全相同

 <bean id="customersServiceImpl" class="cn.csdn.hr.service.CustomersServiceImpl" autowire="byName"/>

 <bean id="customersDao" class="cn.csdn.hr.dao.CustomersDaoImpl"></bean>

 <bean id="baseDao" class="cn.csdn.hr.dao.BaseHibernateDaoImpl"></bean>

 

3.byType    根据指定属性的类型查找相同类型的bean装配。

      注:如果有多个bean匹配会抛异常

        如果没有匹配的一般什么都不会做,如果配置dependency-check="objects"则会抛出异常

属性的类型要和参考bean的class相同

 <bean id="customersServiceImpl" class="cn.csdn.hr.service.CustomersServiceImpl" autowire="byType"/>

 <bean id="customersDaoImpl" class="cn.csdn.hr.dao.CustomersDaoImpl"></bean>

 <bean id="baseDaoImpl" class="cn.csdn.hr.dao.BaseHibernateDaoImpl"></bean>

 

4.constructor  与byType类似,只是用于构造器参数。如果没有在构造器参数中找到类型一致的bean就会抛异常。

要有构造函数。

<bean id="customersServiceImpl" class="cn.csdn.hr.service.CustomersServiceImpl" autowire="constructor"/>

<bean id="customersDaoImpl" class="cn.csdn.hr.dao.CustomersDaoImpl"/>

<bean id="baseDaoImpl" class="cn.csdn.hr.dao.BaseHibernateDaoImpl"/>

 

5.autodetect  通过bean的自省机制决定用byType还是用constructor。如果么有默认构造器则使用byType。

<bean id="customersServiceImpl" class="cn.csdn.hr.service.CustomersServiceImpl" autowire="autodetect" />

<bean id="customersDaoImpl" class="cn.csdn.hr.dao.CustomersDaoImpl" />

<bean id="baseDaoImpl" class="cn.csdn.hr.dao.BaseHibernateDaoImpl" />

 

posted @ 2015-08-04 20:39  爱上咖啡的唐  阅读(181)  评论(0编辑  收藏  举报