[spring]spring的bean自動裝配機制

7.bean的自動裝配

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

spring的裝配方式:

(1)手動裝配

  • 在people類中依賴了cat和dog對象,所以屬性中手動裝配他們的屬性
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns = "//www.springframework.org/schema/beans"
     xmlns:xsi = "//www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation = "//www.springframework.org/schema/beans
        //www.springframework.org/schema/beans/spring-beans.xsd" >

    <bean id="cat" class="pojo.Cat">
        <property name="voice" value="mom~"/>
    </bean>
    <bean id="dog" class="pojo.Dog">
        <property name="voice" value="wow~"/>
    </bean>

 <bean id="people" class="pojo.People">
     <property name="name" value="tata"/>
     <property name="dog" ref="dog"/>
     <property name="cat" ref="cat"/>
 </bean>
</beans>

(2)自動裝配

通過byName自動裝配

  • spring會自動去找people中的set後面相對應的cat和dog與bean中id對應
<bean id="people" class="pojo.People" autowire="byName">
    <property name="name" value="tata"/>

</bean>

通過byType自動裝配

  • spring會自動去找people中的對象依賴和bean中class類相同的對應
<bean id="people" class="pojo.People" autowire="byType">
    <property name="name" value="tata"/>

</bean>

(3)使用註解實現自動裝配

使用之前導入註解依賴的配置和支援

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="//www.springframework.org/schema/beans"
    xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
    xmlns:context="//www.springframework.org/schema/context"
    xsi:schemaLocation="//www.springframework.org/schema/beans
        //www.springframework.org/schema/beans/spring-beans.xsd
        //www.springframework.org/schema/context
        //www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

</beans>

不再使用顯示引用對象依賴的其他屬性

<bean id="cat" class="pojo.Cat"/>
<bean id="dog" class="pojo.Dog"/>
<bean id="people" class="pojo.People"/>

@Autowired

直接在對象上面使用@Autowired註解

private String name;
@Autowired
private Dog dog;
@Autowired
private Cat cat;

如果裝配環境複雜的話,可以通過@Qualifier(value = "cat")指定bean注入

例如多個cat對象bean,屬性值不同的時候

<bean id="cat" class="pojo.Cat">
    <property name="eat" value="fish"/>
</bean>
<bean id="cat11" class="pojo.Cat">
    <property name="eat" value="cookie"/>
</bean>

就需要

@Qualifier

否則,只會spring會走第一個bean

@Autowired
@Qualifier(value = "cat11")
private Cat cat;

Resource

  • 這個註解跟上面的@Autowired功能相似,但是它可以通過名字再通過類型裝配,都沒有才會報錯,要比@Autowired智慧一點,但使用較少。
@Resource(name="cat")
private Cat cat;