[spring]spring的bean自动装配机制

7.bean的自动装配

  • 是spring满足bean依赖的一种方式
  • spring会在上下文中自动寻找,并自动给bean装配属性

spring的装配方式:

(1)手动装配

  • 在people类中依赖了cat和dog对象,所以属性中手动装配他们的属性
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation = "http://www.springframework.org/schema/beans
        http://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="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://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;
posted @ 2022-07-26 17:53  路漫漫qixiuyuanxi  阅读(56)  评论(0编辑  收藏  举报