7 Bean 的自动装配

2023-01-30  本文已影响0人  Messix_1102
  1. 在XML中显式配置
  2. 在java中显式配置
  3. 隐式的自动装配bean 【重要】

7.1 测试

环境搭建:一个人有两个宠物猫和狗

7.2 ByName自动装配

<bean id="cat" class="com.hunter.pojo.Cat"></bean>
<bean id="dog" class="com.hunter.pojo.Dog"></bean>
<!-- 
by name autowired: 会自动在容器上下文中根据Set方法后面的字符串查找对应的beanid
-->
<bean id="human" class="com.hunter.pojo.Human" autowire="byName">
    <property name="name" value="hunter"></property>
</bean>

7.3 ByType自动装配

<!--
by type autowired 会自动在容器上下文中查找类型相同的bean
-->
<bean id="human2" class="com.hunter.pojo.Human" autowire="byType">
    <property name="name" value="hunter"></property>
</bean>

注意:

7.4 使用注解自动装配

JDK 1.5支持的注解,Spring 2.5就支持注解
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.
要使用注解须知:

  1. 导入 context 约束
  2. 配置注解的支持 <context:annotation-config/> 【重要!】
<?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>
    public Human(@Nullable String name){
        this.name = name;
    }
public class Human {
    // @Autowired 有唯一参数required,默认为true
    //如果显示设为false,说明该对象可以为null,否则不允许为空
    @Autowired(required = true)
    public Cat cat;
    @Autowired
    public Dog dog;
    public String name;
}

如果@Autowired 自动装配环境比较复杂,自动装配无法通过一个注解完成的时候,我们们可以使用 @Qualifier(value = "XXX") 配合@Autowired的使用,例如:

bean 配置

<bean id="cat" class="com.hunter.pojo.Cat"></bean>
<bean id="cat2" class="com.hunter.pojo.Cat"></bean>
<bean id="dog" class="com.hunter.pojo.Dog"></bean>
<bean id="dog2" class="com.hunter.pojo.Dog"></bean>
<bean id="human" class="com.hunter.pojo.Human"></bean>

pojo类

public class Human {
    @Autowired
    @Qualifier(value = "cat") // 和@Autowired配合使用
    public Cat cat;
    @Qualifier(value = "dog") // 和@Autowired配合使用
    @Autowired
    public Dog dog;
    public String name;
}
public class Human {
    @Resource(name = "cat")
    public Cat cat;
    @Resource
    public Dog dog;
    public String name;
}

小结:@Resource 和 @Autowired的异同

上一篇 下一篇

猜你喜欢

热点阅读