• Spring自动装配



    自动装配说明

    1. 自动装配是使用spring满足bean依赖的一种方法
    2. spring会在应用上下文中为某个bean寻找其依赖的bean。

    Spring中bean有三种装配机制,分别是:

    • 在xml中显式配置;
    • 在java中显式配置;
    • 隐式的bean发现机制和自动装配。

    这里我们主要讲第三种:自动化的装配bean。

    Spring的自动装配需要从两个角度来实现,或者说是两个操作:

    1. 组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean;
    2. 自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IoC/DI;

    组件扫描和自动装配组合发挥巨大威力,使得显示的配置降低到最少。

    推荐不使用自动装配xml配置 , 而使用注解 .

    测试环境搭建

    1、新建一个项目

    2、新建两个实体类,Cat Dog 都有一个叫的方法

    public class Cat {
        public void shout() {
            System.out.println("miao~");
        }
    }
    public class Dog {
        public void shout() {
            System.out.println("wang~");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    3、新建一个用户类 User

    public class User {
        private Cat cat;
        private Dog dog;
        private String str;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4、编写Spring配置文件

    
    <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="dog" class="com.kuang.pojo.Dog"/>
        <bean id="cat" class="com.kuang.pojo.Cat"/>
        <bean id="user" class="com.kuang.pojo.User">
            <property name="cat" ref="cat"/>
            <property name="dog" ref="dog"/>
            <property name="str" value="qinjiang"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    5、测试

    public class MyTest {
        @Test
        public void testMethodAutowire() {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            User user = (User) context.getBean("user");
            user.getCat().shout();
            user.getDog().shout();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    结果正常输出,环境OK

    byName

    autowire byName (按名称自动装配)

    由于在手动配置xml过程中,常常发生字母缺漏和大小写等错误,而无法对其进行检查,使得开发效率降低。

    采用自动装配将避免这些错误,并且使配置简单化。

    测试:

    1、修改bean配置,增加一个属性 autowire=“byName”

    <bean id="user" class="com.kuang.pojo.User" autowire="byName">
        <property name="str" value="qinjiang"/>
    bean>
    
    • 1
    • 2
    • 3

    2、再次测试,结果依旧成功输出!

    3、我们将 cat 的bean id修改为 catXXX

    4、再次测试, 执行时报空指针java.lang.NullPointerException。因为按byName规则找不对应set方法,真正的setCat就没执行,对象就没有初始化,所以调用时就会报空指针错误。

    小结:
    当一个bean节点带有 autowire byName的属性时。

    1. 将查找其类中所有的set方法名,例如setCat,获得将set去掉并且首字母小写的字符串,即cat。
    2. 去spring容器中寻找是否有此字符串名称id的对象。
    3. 如果有,就取出注入;如果没有,就报空指针异常。

    byType

    autowire byType (按类型自动装配)

    使用autowire byType首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。
    NoUniqueBeanDefinitionException

    测试:

    1、将user的bean配置修改一下 : autowire=“byType”

    2、测试,正常输出

    3、在注册一个cat 的bean对象!

    <bean id="dog" class="com.kuang.pojo.Dog"/>
    <bean id="cat" class="com.kuang.pojo.Cat"/>
    <bean id="cat2" class="com.kuang.pojo.Cat"/>
    <bean id="user" class="com.kuang.pojo.User" autowire="byType">
        <property name="str" value="qinjiang"/>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4、测试,报错:NoUniqueBeanDefinitionException

    5、删掉cat2,将cat的bean名称改掉!测试!因为是按类型装配,所以并不会报异常,也不影响最后的结果。甚至将id属性去掉,也不影响结果。

    这就是按照类型自动装配!

    使用注解

    jdk1.5开始支持注解,spring2.5开始全面支持注解。

    准备工作:利用注解的方式注入属性。

    1、在spring配置文件中引入context文件头

    xmlns:context="http://www.springframework.org/schema/context"
     
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    
    • 1
    • 2
    • 3
    • 4

    2、开启属性注解支持!

    <context:annotation-config/>
    
    • 1

    @Autowired

    @Autowired是按类型自动转配的,不支持id匹配。

    需要导入 spring-aop的包!
    测试:

    1、将User类中的set方法去掉,使用@Autowired注解

    public class User {
        @Autowired
        private Cat cat;
        @Autowired
        private Dog dog;
        private String str;
     
        public Cat getCat() {
            return cat;
        }
        public Dog getDog() {
            return dog;
        }
        public String getStr() {
            return str;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    2、此时配置文件内容

    <context:annotation-config/>
     
    <bean id="dog" class="com.kuang.pojo.Dog"/>
    <bean id="cat" class="com.kuang.pojo.Cat"/>
    <bean id="user" class="com.kuang.pojo.User"/>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3、测试,成功输出结果!

    @Autowired(required=false) 说明:false,对象可以为null;true,对象必须存对象,不能为null。

    //如果允许对象为null,设置required = false,默认为true
    @Autowired(required = false)
    private Cat cat;
    
    • 1
    • 2
    • 3

    @Qualifier

    @Autowired是根据类型自动装配的,加上@Qualifier则可以根据byName的方式自动装配

    @Qualifier不能单独使用。

    测试实验步骤:

    1、配置文件修改内容,保证类型存在对象。且名字不为类的默认名字!

    <bean id="dog1" class="com.kuang.pojo.Dog"/>
    <bean id="dog2" class="com.kuang.pojo.Dog"/>
    <bean id="cat1" class="com.kuang.pojo.Cat"/>
    <bean id="cat2" class="com.kuang.pojo.Cat"/>
    
    • 1
    • 2
    • 3
    • 4

    2、没有加Qualifier测试,直接报错

    3、在属性上添加Qualifier注解

    @Autowired
    @Qualifier(value = "cat2")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog2")
    private Dog dog;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    测试,成功输出!

    @Resource

    @Resource如有指定的name属性,先按该属性进行byName方式查找装配;

    其次再进行默认的byName方式进行装配;

    如果以上都不成功,则按byType的方式自动装配。

    都不成功,则报异常。
    实体类:

    public class User {
        //如果允许对象为null,设置required = false,默认为true
        @Resource(name = "cat2")
        private Cat cat;
        @Resource
        private Dog dog;
        private String str;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    beans.xml
    
    <bean id="dog" class="com.kuang.pojo.Dog"/>
    <bean id="cat1" class="com.kuang.pojo.Cat"/>
    <bean id="cat2" class="com.kuang.pojo.Cat"/>
    <bean id="user" class="com.kuang.pojo.User"/>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    测试:结果OK

    配置文件2:beans.xml , 删掉cat2

    <bean id="dog" class="com.kuang.pojo.Dog"/>
    <bean id="cat1" class="com.kuang.pojo.Cat"/>
    
    • 1
    • 2

    实体类上只保留注解

    @Resource
    private Cat cat;
    @Resource
    private Dog dog;
    
    • 1
    • 2
    • 3
    • 4

    结果:OK
    结论:先进行byName查找,失败;再进行byType查找,成功。
    小结
    @Autowired与@Resource异同:

    1、@Autowired与@Resource都可以用来装配bean。都可以写在字段上,或写在setter方法上。

    2、@Autowired默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用

    3、@Resource(属于J2EE复返),默认按照名称进行装配,名称可以通过name属性进行指定。如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。

    它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired先byType,@Resource先byName。

    注解配置相对于 XML 配置具有很多的优势:

    它可以充分利用 Java 的反射机制获取类结构信息,这些信息可以有效减少配置的工作。如使用 JPA 注释配置 ORM 映射时,我们就不需要指定 PO 的属性名、类型等信息,如果关系表字段和 PO 属性名、类型都一致,您甚至无需编写任务属性映射信息——因为这些信息都可以通过 Java 反射机制获取。
    注释和 Java 代码位于一个文件中,而 XML 配置采用独立的配置文件,大多数配置信息在程序开发完成后都不会调整,如果配置信息和 Java 代码放在一起,有助于增强程序的内聚性。而采用独立的 XML 配置文件,程序员在编写一个功能时,往往需要在程序文件和配置文件中不停切换,这种思维上的不连贯会降低开发效率。
    因此在很多情况下,注释配置比 XML 配置更受欢迎,注释配置有进一步流行的趋势。spring 2.5 的一大增强就是引入了很多注释类,现在您已经可以使用注释配置完成大部分 XML 配置的功能。在这篇文章里,我们将向您讲述使用注释进行 Bean 定义和依赖注入的内容

    使用 context:annotation-config/ 简化配置

    Spring 2.1 添加了一个新的 context 的 Schema 命名空间,该命名空间对注释驱动、属性文件引入、加载期织入等功能提供了便捷的配置。我们知道注释本身是不会做任何事情的,它仅提供元数据信息。要使元数据信息真正起作用,必须让负责处理这些元数据的处理器工作起来。

    而我们前面所介绍的 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor 就是处理这些注释元数据的处理器。但是直接在 Spring 配置文件中定义这些 Bean 显得比较笨拙。Spring 为我们提供了一种方便的注册这些BeanPostProcessor 的方式,这就是 context:annotation-config/。请看下面的配置:

    调整 beans.xml 配置文件

    
    <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 
     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context-2.5.xsd">
     
        <context:annotation-config/> 
    
        <bean id="boss" class="com.baobaotao.Boss"/>
        <bean id="office" class="com.baobaotao.Office">
            <property name="officeNo" value="001"/>
        bean>
        <bean id="car" class="com.baobaotao.Car" scope="singleton">
            <property name="brand" value=" 红旗 CA72"/>
            <property name="price" value="2000"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    context:annotationconfig/ 将隐式地向 Spring 容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 以及equiredAnnotationBeanPostProcessor 这 4 个 BeanPostProcessor。
    在配置文件中使用 context 命名空间之前,必须在 元素中声明 context 命名空间。

    使用 @Component

    虽然我们可以通过 @Autowired 或 @Resource 在 Bean 类中使用自动注入功能,但是 Bean 还是在 XML 文件中通过 进行定义 —— 也就是说,在 XML 配置文件中定义 Bean,通过@Autowired 或 @Resource 为 Bean 的成员变量、方法入参或构造函数入参提供自动注入的功能。能否也通过注解定义 Bean,从 XML 配置文件中完全移除 Bean 定义的配置呢?答案是肯定的,我们通过 Spring 2.5 提供的@Component 注释就可以达到这个目标了。

    为什么 @Repository 只能标注在 DAO 类上呢?这是因为该注解的作用不只是将类识别为 Bean,同时它还能将所标注的类中抛出的数据访问异常封装为 Spring 的数据访问异常类型。 Spring 本身提供了一个丰富的并且是与具体的数据访问技术无关的数据访问异常结构,用于封装不同的持久层框架抛出的异常,使得异常独立于底层的框架。

    Spring 2.5 在 @Repository 的基础上增加了功能类似的额外三个注解:@Component、@Service、@Constroller,它们分别用于软件系统的不同层次:

    @Component 是一个泛化的概念,仅仅表示一个组件 (Bean) ,可以作用在任何层次。
    @Service 通常作用在业务层,但是目前该功能与 @Component 相同。
    @Constroller 通常作用在控制层,但是目前该功能与 @Component 相同。
    通过在类上使用 @Repository、@Component、@Service 和 @Constroller 注解,Spring 会自动创建相应的 BeanDefinition 对象,并注册到 ApplicationContext 中。这些类就成了 Spring 受管组件。这三个注解除了作用于不同软件层次的类,其使用方式与 @Repository 是完全相同的。

    下面,我们完全使用注释定义 Bean 并完成 Bean 之间装配:
    使用 @Component 注释的 Car.java

    package com.baobaotao;
    
    import org.springframework.stereotype.Component;
    
    @Component
    public class Car {}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    仅需要在类定义处,使用 @Component 注解就可以将一个类定义了 Spring 容器中的 Bean。下面的代码将 Office 定义为一个 Bean:

    使用 @Component 注释的 Office.java

    package com.baobaotao;
    
    import org.springframework.stereotype.Component;
    
    @Component
    public class Office {
        private String officeNo = "001";}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    这样,我们就可以在 Boss 类中通过 @Autowired 注入前面定义的 Car 和 Office Bean 了。

    使用 @Component 注释的 Boss.java

    package com.baobaotao;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Required;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Component;
    
    @Component("boss")
    public class Boss {
        @Autowired
        private Car car;
    
        @Autowired
        private Office office;}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    @Component 有一个可选的入参,用于指定 Bean 的名称,在 Boss 中,我们就将 Bean 名称定义为“boss”。一般情况下,Bean 都是 singleton 的,需要注入 Bean 的地方仅需要通过 byType 策略就可以自动注入了,所以大可不必指定 Bean 的名称。

    在使用 @Component 注解后,Spring 容器必须启用类扫描机制以启用注解驱动 Bean 定义和注解驱动 Bean 自动注入的策略。Spring 2.5 对 context 命名空间进行了扩展,提供了这一功能,请看下面的配置:
    简化版的 beans.xml

    
    <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 
     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context-2.5.xsd">
        <context:component-scan base-package="com.baobaotao"/>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    这里,所有通过 元素定义 Bean 的配置内容已经被移除,仅需要添加一行 context:component-scan/ 配置就解决所有问题了——Spring XML 配置文件得到了极致的简化(当然配置元数据还是需要的,只不过以注释形式存在罢了)。context:component-scan/ 的 base-package 属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。

    context:component-scan/ 还允许定义过滤器将基包下的某些类纳入或排除。Spring 支持以下 4 种类型的过滤方式,通过下表说明:

    表 1. 扫描过滤方式
    过滤器类型 说明注解 假如 com.baobaotao.SomeAnnotation 是一个注解类,我们可以将使用该注解的类过滤出来。
    类名指定 通过全限定类名进行过滤,如您可以指定将 com.baobaotao.Boss 纳入扫描,而将 com.baobaotao.Car 排除在外。
    正则表达式 通过正则表达式定义过滤的类,如下所示: com.baobaotao.Default.*
    AspectJ 表达式 通过 AspectJ 表达式定义过滤的类,如下所示: com. baobaotao…*Service+
    下面是一个简单的例子:

    <context:component-scan base-package="com.baobaotao">
        <context:include-filter type="regex" 
            expression="com\.baobaotao\.service\..*"/>
        <context:exclude-filter type="aspectj" 
            expression="com.baobaotao.util..*"/>
    context:component-scan>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    值得注意的是 context:component-scan/ 配置项不但启用了对类包进行扫描以实施注释驱动 Bean 定义的功能,同时还启用了注解驱动自动注入的功能(即还隐式地在内部注册了AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor),因此当使用 context:component-scan/ 后,就可以将 context:annotation-config/ 移除了。
    默认情况下通过 @Component 定义的 Bean 都是 singleton 的,如果需要使用其它作用范围的 Bean,可以通过@Scope 注释来达到目标,如以下代码所示:
    @scopee
    通过 @Scope 指定 Bean 的作用范围

    package com.baobaotao;
    import org.springframework.context.annotation.Scope;@Scope("prototype")
    @Component("boss")
    public class Boss {}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    这样,当从 Spring 容器中获取 boss Bean 时,每次返回的都是新的实例了。
    采用具有特殊语义的注释

    Spring 2.5 中除了提供 @Component 注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository、@Service 和@Controller。在目前的 Spring 版本中,这 3 个注释和 @Component 是等效的,但是从注释类的命名上,很容易看出这 3 个注释分别和持久层、业务层和控制层(Web 层)相对应。虽然目前这 3 个注释和@Component 相比没有什么新意,但 Spring 将在以后的版本中为它们添加特殊的功能。所以,如果 Web 应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用@Repository、@Service 和 @Controller 对分层中的类进行注释,而用@Component 对那些比较中立的类进行注释。

    注解配置和 XML 配置的适用场合

    是否有了这些 IOC 注解,我们就可以完全摒除原来 XML 配置的方式呢?答案是否定的。有以下几点原因:

    注解配置不一定在先天上优于 XML 配置。如果 Bean 的依赖关系是固定的,(如 Service 使用了哪几个 DAO 类),这种配置信息不会在部署时发生调整,那么注释配置优于 XML 配置;反之如果这种依赖关系会在部署时发生调整,XML 配置显然又优于注解配置,因为注解是对 Java 源代码的调整,您需要重新改写源代码并重新编译才可以实施调整。
    如果 Bean 不是自己编写的类(如 JdbcTemplate、SessionFactoryBean 等),注解配置将无法实施,此时 XML 配置是唯一可用的方式。
    注解配置往往是类级别的,而 XML 配置则可以表现得更加灵活。比如相比于 @Transaction 事务注释,使用 aop/tx 命名空间的事务配置更加灵活和简单。
    所以在实现应用中,我们往往需要同时使用注解配置和 XML 配置,对于类级别且不会发生变动的配置可以优先考虑注解配置;而对于那些第三方类以及容易发生调整的配置则应优先考虑使用 XML 配置。Spring 会在具体实施 Bean 创建和 Bean 注入之前将这两种配置方式的元信息融合在一起。

  • 相关阅读:
    Flink SQL搭建实时数仓DWD层
    代码随想录算法训练营第二十四天| LeetCode77. 组合
    【SpringCloud】Eureka注册中心 代码详细介绍
    Linux定时任务详解
    主流数据库之索引及其例子
    MongoDB - 非关系型数据库概念
    elf 文件信息的用途
    【 C++ 】stack、queue、优先级队列、仿函数、容器适配器
    Power Automate-时间戳转化为时区时间
    MongoDB CRUD操作:可重试写入
  • 原文地址:https://blog.csdn.net/qq_41512902/article/details/126140352