首页 > Spring框架中autowire,by name和by type有什么区别

Spring框架中autowire,by name和by type有什么区别

下面代码autowire="byName"意思是通过id="userDao"来查找Bean中的userDao对象是吗?

      若autowire="byType"意思是通过 class="cn.com.bochy.dao.impl.UserDaoImpl"来查找UserDaoImpl下所有的对象。

这样理解对吗??

<bean id="userServiceImpl"
            class="cn.com.bochy.service.impl.UserServiceImpl"
            autowire="byName">
       </bean>  
      <bean id="userDao"                                         

             class="cn.com.bochy.dao.impl.UserDaoImpl">
</bean>

这个问题已解决,总结如下:
spring中装配bean的基础知识如下:
1.<bean id="" class="">,bean是spring中最基本的配置单元,通过<bean>spring将创建一个对象。id属性定义了bean的名字,同时也作为该bean在spring容器中的引用。


Spring里,autowire="byName"的意思是,如果一个beanname和另一个bean里某一个属性名相同,自动关联。

如下例子,customer是一个bean,她有一个叫address的属性,Spring会在当前容器里找一个叫addressbean并把他们关联起来。没找到,就啥也不做。

<!-- customer has a property name "address" -->
<bean id="customer" class="com.test.common.Customer" autowire="byName" />
    
<bean id="address" class="com.test.common.Address" >
    <property name="fulladdress" value="Block A 888, CA" />
</bean>

customer

package com.test.common;
 
public class Customer 
{
    private Address address;
    //...
}

address

package com.test.common;
 
public class Address 
{
    private String fulladdress;
    //...
}

建议看 《Spring in Action》 第三章第一节,“自动装配 Bean 属性”


byName就是通过Bean的id或者name,byType就是按Bean的Class的类型。

【热门文章】
【热门文章】