博客 / 詳情

返回

Bean的裝配方式

在Spring中有三種裝配的方式:

  1. 在xml中顯式的配置
  2. 在java中顯式的配置
  3. 隱式的自動裝配bean

在xml中顯式的配置

引用 Spring-IOC創建對象的方式

在xml文件中配置對象屬性

在java中顯式的配置

引用 Spring-IOC理論推導

在實際調用dao層的時候,可以顯示的配置選用哪個dao接口

隱式的自動裝配bean

  • 自動裝配是Spring滿足bean依賴的一種方式
  • Spring會在上下文中自動尋找,並自動給bean裝配屬性

byName自動裝配

<bean id="cat" class="com.sunfl.pojo.Cat"/>
<bean id="dog" class="com.sunfl.pojo.Dog"/>

<!--
byName:會自動在容器上下文查找,和自己對象set方法後面的值對應的beanid!
-->
<bean id="people" class="com.sunfl.pojo.People" autowire="byName">
    <property name="name" value="向日葵"/>
</bean>

byType自動裝配

<bean id="cat" class="com.sunfl.pojo.Cat"/>
<bean id="dog111" class="com.sunfl.pojo.Dog"/>

<!--
byType:會自動在容器上下文查找,和自己對象屬性類型相同的bean!
-->
<bean id="people" class="com.sunfl.pojo.People" autowire="byType">
    <property name="name" value="向日葵"/>
</bean>

小結:

  • byName的時候,需要保證所有的bean的id唯一,並且這個bean需要和自動注入的屬性set方法的值一致
  • byType的時候,需要保證所有的bean的class唯一,並且這個bean需要和自動注入的屬性類型一致

使用註解實現自動裝配

jdk1.5支持註解,Spring2.5支持註解

  1. 導入約束:context約束
  2. 配置註解的支持:

    <?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"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd">
    
     <bean id="cat" class="com.sunfl.pojo.Cat"/>
     <bean id="dog" class="com.sunfl.pojo.Dog"/>
     <bean id="people" class="com.sunfl.pojo.People"/>
    
     <!--開啓註解的支持-->
     <context:annotation-config/>
    
    </beans>
    

@Autowired
直接在屬性上使用即可,也可以在set方法上使用
使用Autowired我們可以不用編寫Set方法了,前提是你這個自動裝配的屬性在IOC(Spring)容器中存在,且符合名字byName

如果@Autowired自動裝配的環境比較複雜,自動裝配無法通過一個註解【@Autowired】完成的時候,我們可以使用@Qualifier(value="xxx")去配置@Autowired的使用,指定一個唯一的bean對象注入

public class People {

    @Autowired
    @Qualifier(value = "cat111")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog222")
    private Dog dog;
    private String name;
}

@Resource註解

public class People {

    @Resource(name = "cat2")
    private Cat cat;

    @Resource
    private Dog dog;
    private String name;
}

小結:
@Resource和@Autowired的區別:

  • 都是用來自動裝配的,都可以放在屬性字段上
  • @Autowired通過byType的方式實現【常用】
  • @Resource默認通過byName的方式實現,如果找不到名字,則通過byType實現
user avatar xuezhongyu01 頭像 madrid 頭像
2 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.