其他分享
首页 > 其他分享> > [spring]spring的bean自动装配机制

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

作者:互联网

7.bean的自动装配

spring的装配方式:

(1)手动装配

<?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自动装配

<bean id="people" class="pojo.People" autowire="byName">
    <property name="name" value="tata"/>

</bean>

通过byType自动装配

<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

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

标签:装配,Autowired,spring,cat,bean,自动
来源: https://www.cnblogs.com/lumanmanqixiuyuanxi/p/16521978.html