• 自动装配说明



    学习视频来自于:秦疆(遇见狂神说)Bilibili地址
    他的自学网站:kuangstudy

    但行好事,莫问前程


    一、自动装配

    1.1 介绍

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

    Spring中bean有三种装配机制

    1. 在xml中显式配置。
    2. 在java中显式配置。
    3. 隐式的bean发现机制和自动装配。

    1.2 自动化的装配bean

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

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

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

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

    1.3 测试环境搭建

    实体类

    Cat.java

    public class Cat {
       public void shout() {
           System.out.println("miao~");
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Dog.java

    public class Dog {
       public void shout() {
           System.out.println("wang~");
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    User.java

    public class User {
        private Cat cat;
        private Dog dog;
        private String str;
    
        public Cat getCat() {
            return cat;
        }
    
        public void setCat(Cat cat) {
            this.cat = cat;
        }
    
        public Dog getDog() {
            return dog;
        }
    
        public void setDog(Dog dog) {
            this.dog = dog;
        }
    
        public String getStr() {
            return str;
        }
    
        public void setStr(String str) {
            this.str = str;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

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

    测试

    public class UserTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
            User user = context.getBean("user", User.class);
            user.getDog().shout();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    结果正常输出,环境OK

    1.4 byName自动装配

    autowire byName (按名称自动装配)

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

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

    测试:

    1. 修改bean配置,增加一个属性 autowire=“byName”
    <bean id="dog" class="pers.tianyu.pojo.Dog"/>
    <bean id="cat" class="pers.tianyu.pojo.Cat"/>
    
    <bean id="user" class="pers.tianyu.pojo.User" autowire="byName">
            <property name="str" value="tianyu"/>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

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

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

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

    1.5 byType自动装配

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

    NoUniqueBeanDefinitionException
    
    • 1

    测试:

    1. 将user的bean配置修改一下 : autowire=“byType”
    2. 测试,正常输出
    3. 在注册一个cat 的bean对象!
    <bean id="dog" class="pers.tianyu.pojo.Dog"/>
    <bean id="cat" class="pers.tianyu.pojo.Cat"/>
    
    <bean id="user" class="pers.tianyu.pojo.User" autowire="byType">
       <property name="str" value="tianyu"/>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    1. 如果同一个对象不唯一,回报
    NoUniqueBeanDefinitionException
    
    • 1

    1.6 使用注解实现自动装配

    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
    1. 开启属性注解支持!
    <context:annotation-config/>
    
    • 1

    1.7 @Autowired

    • @Autowired是先按类型在按名字匹配,不支持id匹配。
    • 需要导入 spring-aop的包!

    测试
    将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
    • 18
    • 19

    spring配置文件

    
    <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.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">
           
        <context:annotation-config/>
        
        <bean id="dog" class="pers.tianyu.pojo.Dog"/>
        <bean id="cat" class="pers.tianyu.pojo.Cat"/>
        <bean id="user" class="pers.tianyu.pojo.User"/>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

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

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

    如果配置文件中,一个类型有两个bean,就按byName

    1.8 @Qualifier

    • @Autowired是根据类型或名字自动装配的,加上@Qualifier则可以根据byName的方式自动装配
    • @Qualifier不能单独使用。
    • 可以自定义别名,用于匹配容器中的类

    测试

    1. 配置文件修改内容,保证类型存在对象。且名字不为类的默认名字!
    <bean id="dog1" class="pers.tianyu.pojo.Dog"/>
    <bean id="cat1" class="pers.tianyu.pojo.Cat"/>
    
    <bean id="user" class="pers.tianyu.pojo.User"/>
    
    • 1
    • 2
    • 3
    • 4
    1. 没有加Qualifier测试,直接报错
    2. 在属性上添加Qualifier注解
    public class User {
        @Autowired
        @Qualifier(value = "cat1")
        private Cat cat;
        @Autowired
        @Qualifier(value = "dog1")
        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
    • 18
    • 19
    • 20
    • 21

    测试,成功输出!

    1.9 @Resource

    • @Resource如有指定的name属性,先按该属性进行byName方式查找装配;
    • 其次再进行默认的byName方式进行装配;
    • 如果以上都不成功,则按byType的方式自动装配。
    • 都不成功,则报异常。

    实体类

    public class User {
        @Resource(name = "cat1")
        private Cat cat;
        @Resource
        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
    • 18
    • 19

    配置文件

    <context:annotation-config/>
    <bean id="dog" class="pers.tianyu.pojo.Dog"/>
    <bean id="cat1" class="pers.tianyu.pojo.Cat"/>
    <bean id="cat2" class="pers.tianyu.pojo.Cat"/>
    <bean id="user" class="pers.tianyu.pojo.User"/>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    测试:结果OK

    当类型不重复,名字没有指定也是可以自动注入

    public class User {
        @Resource
        private Cat cat;
        @Resource
        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
    • 18
    • 19
    <context:annotation-config/>
    <bean id="dog" class="pers.tianyu.pojo.Dog"/>
    <bean id="cat2" class="pers.tianyu.pojo.Cat"/>
    
    <bean id="user" class="pers.tianyu.pojo.User"/>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    结果: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属性一旦指定,就只会按照名称进行装配。

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

  • 相关阅读:
    抖音短视频矩阵系统多账号矩阵源头开发源码分享
    HTML-CSS练习例子
    CentOS系统环境搭建(十八)——CentOS7安装Docker20.10.12和docker compose v2
    题目 1053: 二级C语言-平均值计算
    GEE入门篇|图像处理(二):在Earth Engine中进行波段计算
    Java版工程行业管理系统源码-专业的工程管理软件- 工程项目各模块及其功能点清单
    生成扩散模型漫谈:最优扩散方差估计(上)
    部署ai画图服务器
    PostGIS简单使用
    Linux 权限维持手法
  • 原文地址:https://blog.csdn.net/zhao854116434/article/details/126160264