Bean的自动装配

发布时间 2023-04-08 21:58:10作者: gyViolet
  • 自动装配是Spring满足bean依赖的一种方式
  • Spring会在上下文中自动寻找,并自动给bean装配属性

在spring中有3种装配的方式

  1. 在xml中显式装配
  2. 在Java中显式装配
  3. 隐式的自动装配bean(重点)

测试

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

ByName/ByType自动装配

 <bean id="cat" class="com.gy.pojo.Cat"/>
    <bean id="dog" class="com.gy.pojo.Dog"/>
    <!--
    byName:会自动在容器上下文中查找和自己对象set方法后面对应的beanid
    byType:根据属性的数据类型自动装配(dog111或者去掉id都可找到)

    -->
    <bean id="people" class="com.gy.pojo.People" autowire="byType">
        <property name="name" value="alice"/>
<!--        <property name="cat" ref="cat"/>-->
<!--        <property name="dog" ref="dog"/>-->
    </bean>

注意:xml的优点就是可以对bean进行集中式管理,注解则比较分散

使用注解实现自动装配

jdk1.5支持的注解,Spring2.5支持注解
要使用注解须知:
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"
       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">
    <!--开启注解的支持-->
    <context:annotation-config/>
    <bean id="cat" class="com.gy.pojo.Cat"/>
    <bean id="dog" class="com.gy.pojo.Dog"/>
    <bean id="people" class="com.gy.pojo.People"/>

</beans>

Autowired及其他注解

  • 可以不编写Set方法,前提是自动装配的属性在IOC(Spring)容器中存在且符合名字byname.
  • 需要导入 spring-aop的包!
  • @Autowired是根据类型自动装配的,加上@Qualifier则可以根据byName的方式自动装配
  • @Nullable 赋值失败不报错,默认赋值null
  • @Component:组件,放在类上,说明这个类被spring管理了,即bean
public @interface Autowired {
    boolean required() default true;
}

测试

public class People {
    //如果显式定义了Autowired的require为false表示允许cat在容器中不存在
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
  • @Qualifier不能单独使用。
public class People {
    @Autowired
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog222")
    private Dog dog;
    private String name;
  • @Resource有版本兼容问题,用的话可以解决spring代码耦合,但是在jdk1.8以后没有@Resource这个注解了

小结

@Autowired与@Resource异同:
@Autowired与@Resource都可以用来装配bean。都可以写在字段上,或写在setter方法上。
@Autowired默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用
@Resource(属于J2EE复返),默认按照名称进行装配,名称可以通过name属性进行指定。如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。 当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。
它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired先byType,@Resource先byName。