• Spring6 - ioc


    IoC容器

    什么叫ioc呢?控制反转(IoC)

    • 控制反转是一种思想。

    • 控制反转是为了降低程序耦合度,提高程序扩展力。

    • 控制反转,反转的是什么?

      • 将对象的创建权利交出去,交给第三方容器负责。
      • 将对象和对象之间关系的维护权交出去,交给第三方容器负责。
    • 控制反转这种思想如何实现呢?

    通过依赖注入实现

    依赖注入:

    • 指Spring创建对象的过程中,将对象依赖属性通过配置进行注入

    依赖注入常见的实现方式包括两种:

    • 第一种:set注入
    • 第二种:构造注入

    所以结论是:IOC 就是一种控制反转的思想, 而 DI 是对IoC的一种具体实现。

    Bean管理说的是:Bean对象的创建,以及Bean对象中属性的赋值(或者叫做Bean对象之间关系的维护)。

    IoC容器在Spring的实现

    Spring 的 IoC 容器就是 IoC思想的一个落地的产品实现。IoC容器中管理的组件也叫做 bean。在创建 bean 之前,首先需要创建IoC 容器。Spring 提供了IoC 容器的两种实现方式:
    ①BeanFactory

    这是 IoC 容器的基本实现,是 Spring 内部使用的接口。面向 Spring 本身,不提供给开发人员使用。

    ②ApplicationContext

    BeanFactory 的子接口,提供了更多高级特性。面向 Spring 的使用者,几乎所有场合都使用 ApplicationContext 而不是底层的 BeanFactory。

    ③ApplicationContext的主要实现类
    在这里插入图片描述

    类型名简介
    ClassPathXmlApplicationContext通过读取类路径下的 XML 格式的配置文件创建 IOC 容器对象
    FileSystemXmlApplicationContext通过文件系统路径读取 XML 格式的配置文件创建 IOC 容器对象
    ConfigurableApplicationContextApplicationContext 的子接口,包含一些扩展方法 refresh() 和 close() ,让 ApplicationContext 具有启动、关闭和刷新上下文的能力。
    WebApplicationContext专门为 Web 应用准备,基于 Web 环境创建 IOC 容器对象,并将对象引入存入 ServletContext 域中。

    基于XML管理Bean

    首先建立好spring的相关环境

    获取bean

    基本的环境先建立好
    建立helloWord.java
    在这里插入图片描述

    public class HelloWorld {
    
        public HelloWorld() {
            System.out.println("这个是一个无参的构造方法!!");
        }
    
        public void sayHello(){
            System.out.println("helloworld");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    在resources建立xml文件
    在这里插入图片描述
    里面写helloWord的配置

    
    <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="helloWorld" class="com.test.HelloWorld">bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    ①方式一:根据id获取

    由于 id 属性指定了 bean 的唯一标识,所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。

        @Test
        void test(){
            ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
            HelloWorld HI = (HelloWorld) ac.getBean("helloWorld");
            HI.sayHello();
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    ②方式二:根据类型获取

    @Test
    public void testHelloWorld1(){
    	ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        HelloWorld bean = ac.getBean(HelloWorld.class);
        bean.sayHello();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    注意:当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个

    当IOC容器中一共配置了两个:

    <bean id="helloworldOne" class="com.test.spring6.bean.HelloWorld">bean>
    <bean id="helloworldTwo" class="com.test.spring6.bean.HelloWorld">bean>
    
    • 1
    • 2

    根据类型获取时会抛出异常

    ③方式三:根据id和类型

    @Test
    public void testHelloWorld2(){
    	ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        HelloWorld bean = ac.getBean("helloworld", HelloWorld.class);
        bean.sayHello();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    ④扩展知识

    如果组件类实现了接口,根据接口类型可以获取 bean 吗?

    可以,前提是bean唯一

    如果一个接口有多个实现类,这些实现类都配置了 bean,根据接口类型可以获取 bean 吗?

    不行,因为bean不唯一

    结论

    根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类型』的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。

    java中,instanceof运算符用于判断前面的对象是否是后面的类,或其子类、实现类的实例。如果是返回true,否则返回false。也就是说:用instanceof关键字做判断时, instanceof 操作符的左右操作必须有继承或实现关系

    依赖注入之setter注入

    ①创建学生类Student

    
    public class Student {
    
        private Integer id;
    
        private String name;
    
        private Integer age;
    
        private String sex;
    
        public Student() {
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    ", sex='" + sex + '\'' +
                    '}';
        }
    
    }
    
    • 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
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    ②配置bean时为属性赋值
    spring-di.xml

    
    <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="studentOne" class="com.test.Student">
            
            
            
            <property name="id" value="1001">property>
            <property name="name" value="张三">property>
            <property name="age" value="23">property>
            <property name="sex" value="">property>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    ③测试

    @Test
    public void testDIBySet(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-di.xml");
        Student studentOne = ac.getBean("studentOne", Student.class);
        System.out.println(studentOne);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    依赖注入之构造器注入

    ①在Student类中添加有参构造
    student.java 代码如下:

    package com.test;
    
    
    
    public class Student {
    
        private Integer id;
    
        private String name;
    
        private Integer age;
    
        private String sex;
    
        public Student() {
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
        public Student(Integer id, String name, Integer age, String sex) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    ", sex='" + sex + '\'' +
                    '}';
        }
    
    }
    
    • 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
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65

    ②配置bean

        <bean id="studentTwo" class="com.test.Student">
            <constructor-arg value="1002">constructor-arg>
            <constructor-arg value="李四">constructor-arg>
            <constructor-arg value="33">constructor-arg>
            <constructor-arg value="">constructor-arg>
        bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    注意:

    constructor-arg标签还有两个属性可以进一步描述构造器参数:

    • index属性:指定参数所在位置的索引(从0开始)
    • name属性:指定参数名

    ③测试

    @Test
    public void testDIByConstructor(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-di.xml");
        Student studentOne = ac.getBean("studentTwo", Student.class);
        System.out.println(studentOne);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    特殊值处理

    ①字面量赋值

    什么是字面量?

    int a = 10;

    声明一个变量a,初始化为10,此时a就不代表字母a了,而是作为一个变量的名字。当我们引用a的时候,我们实际上拿到的值是10。

    而如果a是带引号的:‘a’,那么它现在不是一个变量,它就是代表a这个字母本身,这就是字面量。所以字面量没有引申含义,就是我们看到的这个数据本身。

    
    <property name="name" value="张三"/>
    
    • 1
    • 2

    ②null值

    <property name="name">
        <null />
    </property>
    
    • 1
    • 2
    • 3

    注意:

    <property name="name" value="null">property>
    
    • 1

    以上写法,为name所赋的值是字符串null

    ③xml实体

    
    
    <property name="expression" value="a < b"/>
    
    • 1
    • 2
    • 3

    ④CDATA节

    <property name="expression">
        
        
        
        
        <value>value>
    property>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    为对象类型属性赋值

    现在的情景 Clazz 是一个类对象
    student 是一个类对象里面有 Clazz的属性,
    现在要把Clazz注入到student类里面

    注意:(要有set xxxx 方法)

    方式一:引用外部bean
    配置Clazz类型的bean:

    <bean id="clazzOne" class="com.test.Clazz">
    
        <property name="clazzId" value="1111">property>
        <property name="clazzName" value="财源滚滚班">property>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    为Student中的clazz属性赋值:

    <bean id="studentFour" class="com.test.Student">
        <property name="id" value="1004">property>
        <property name="name" value="赵六">property>
        <property name="age" value="26">property>
        <property name="sex" value="">property>
        
        <property name="clazz" ref="clazzOne">property>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    方式二:内部bean

    <bean id="studentFour" class="com.test.Student">
        <property name="id" value="1004">property>
        <property name="name" value="赵六">property>
        <property name="age" value="26">property>
        <property name="sex" value="">property>
        <property name="clazz">
            
            
            <bean id="clazzInner" class="com.test.Clazz">
                <property name="clazzId" value="2222">property>
                <property name="clazzName" value="远大前程班">property>
            bean>
        property>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    方式三:级联属性赋值

    <bean id="studentFour" class="com.test.Student">
        <property name="id" value="1004">property>
        <property name="name" value="赵六">property>
        <property name="age" value="26">property>
        <property name="sex" value="">property>
        <property name="clazz" ref="clazzOne">property>
        <property name="clazz.clazzId" value="3333">property>
        <property name="clazz.clazzName" value="最强王者班">property>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    为数组类型属性赋值

    情况说明 :student类下有一个爱好列表(String[] hobbies),要为student给他附上这些属性。
    注意:(要有set xxxx 方法)

    <bean id="studentFour" class="com.test.Student">
        <property name="id" value="1004">property>
        <property name="name" value="赵六">property>
        <property name="age" value="26">property>
        <property name="sex" value="">property>
        
        <property name="clazz" ref="clazzOne">property>
        <property name="hobbies">
            <array>
                <value>抽烟value>
                <value>喝酒value>
                <value>烫头value>
            array>
        property>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    为集合类型属性赋值

    情况:Clazz 里面有一个
    private List students;(集合类属性)
    该如何使用xml注入呢!
    注意:(要有set xxxx 方法)

    <bean id="clazzTwo" class="com.atguigu.spring6.bean.Clazz">
        <property name="clazzId" value="4444">property>
        <property name="clazzName" value="Javaee0222">property>
        <property name="students">
            <list>
            
    
                <ref bean="studentOne">ref>
                <ref bean="studentTwo">ref>
                <ref bean="studentThree">ref>
            list>
        property>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    若为Set集合类型属性赋值,只需要将其中的list标签改为set标签即可

    ②为Map集合类型属性赋值

    在student类里面有集合
    private Map teacherMap;
    这种属性

    注意:(要有set xxxx 方法)

    <bean id="teacherOne" class="com.test.Teacher">
        <property name="teacherId" value="10010">property>
        <property name="teacherName" value="大宝">property>
    bean>
    
    <bean id="teacherTwo" class="com.test.Teacher">
        <property name="teacherId" value="10086">property>
        <property name="teacherName" value="二宝">property>
    bean>
    
    <bean id="studentFour" class="com.test.Student">
        <property name="id" value="1004">property>
        <property name="name" value="赵六">property>
        <property name="age" value="26">property>
        <property name="sex" value="">property>
        
        <property name="clazz" ref="clazzOne">property>
        
        <property name="teacherMap">
            <map>
                <entry>
                    <key>
                        <value>10010value>
                    key>
                    <ref bean="teacherOne">ref>
                entry>
                <entry>
                    <key>
                        <value>10086value>
                    key>
                    <ref bean="teacherTwo">ref>
                entry>
            map>
        property>
    bean>
    
    • 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
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    ③引用集合类型的bean

    
    <util:list id="students">
        <ref bean="studentOne">ref>
        <ref bean="studentTwo">ref>
        <ref bean="studentThree">ref>
    util:list>
    
    <util:map id="teacherMap">
        <entry>
            <key>
                <value>10010value>
            key>
            <ref bean="teacherOne">ref>
        entry>
        <entry>
            <key>
                <value>10086value>
            key>
            <ref bean="teacherTwo">ref>
        entry>
    util:map>
    <bean id="clazzTwo" class="com.test.Clazz">
        <property name="clazzId" value="4444">property>
        <property name="clazzName" value="Javaee0222">property>
        <property name="students" ref="students">property>
    bean>
    <bean id="studentFour" class="com.test.Student">
        <property name="id" value="1004">property>
        <property name="name" value="赵六">property>
        <property name="age" value="26">property>
        <property name="sex" value="">property>
        
        <property name="clazz" ref="clazzOne">property>
        <property name="hobbies">
            <array>
                <value>抽烟value>
                <value>喝酒value>
                <value>烫头value>
            array>
        property>
        <property name="teacherMap" ref="teacherMap">property>
    bean>
    
    • 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
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    使用util:list、util:map标签必须引入相应的命名空间

    
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:util="http://www.springframework.org/schema/util"
        xsi:schemaLocation="http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    p命名空间

    引入p命名空间

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:util="http://www.springframework.org/schema/util"
           xmlns:p="http://www.springframework.org/schema/p"
           xsi:schemaLocation="http://www.springframework.org/schema/util
           http://www.springframework.org/schema/util/spring-util.xsd
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    引入p命名空间后,可以通过以下方式为bean的各个属性赋值(和上面的util相似)

    <bean id="studentSix" class="com.test.Student"
        p:id="1006" p:name="小明" p:clazz-ref="clazzOne" p:teacherMap-ref="teacherMap">bean>
    
    • 1
    • 2

    引入外部属性文件

    ①加入依赖

    <!-- MySQL驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.30</version>
    </dependency>
    
    <!-- 数据源 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.2.15</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    ②创建外部属性文件
    在这里插入图片描述

    jdbc.user=root
    jdbc.password=123456
    jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
    jdbc.driver=com.mysql.cj.jdbc.Driver
    
    • 1
    • 2
    • 3
    • 4

    ③引入属性文件

    引入context 名称空间

    
    <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:property-placeholder location="classpath:jdbc.properties"/>
    
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    注意:在使用 context:property-placeholder 元素加载外包配置文件功能前,首先需要在 XML 配置的一级标签 中添加 context 相关的约束。

    ④配置bean
    也就是上面文件续写。。。

    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    ⑤测试

    @Test
    public void testDataSource() throws SQLException {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-datasource.xml");
        DataSource dataSource = ac.getBean(DataSource.class);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    bean的作用域

    ①概念

    在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围,各取值含义参加下表:

    取值含义创建对象的时机
    singleton(默认)在IOC容器中,这个bean的对象始终为单实例IOC容器初始化时
    prototype这个bean在IOC容器中有多个实例获取bean时

    如果是在WebApplicationContext环境下还会有另外几个作用域(但不常用):

    取值含义
    request在一个请求范围内有效
    session在一个会话范围内有效

    ②创建类User

    public class User {
    
        private Integer id;
    
        private String username;
    
        private String password;
    
        private Integer age;
    
        public User() {
        }
    
        public User(Integer id, String username, String password, Integer age) {
            this.id = id;
            this.username = username;
            this.password = password;
            this.age = age;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", username='" + username + '\'' +
                    ", password='" + password + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    
    • 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
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62

    ③配置bean

    
    <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 class="com.test.User" scope="prototype">bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    ④测试

        @Test
        public void testBeanScope(){
            ApplicationContext ac = new ClassPathXmlApplicationContext("spring-scope.xml");
            // 可以获取多个对象
            User user1 = ac.getBean(User.class);
            User user2 = ac.getBean(User.class);
            System.out.println(user1==user2);//false
        }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    bean生命周期

    ①具体的生命周期过程

    • bean对象创建(调用无参构造器)

    • 给bean对象设置属性

    • bean的后置处理器(初始化之前)

    • bean对象初始化(需在配置bean时指定初始化方法)

    • bean的后置处理器(初始化之后)

    • bean对象就绪可以使用

    • bean对象销毁(需在配置bean时指定销毁方法)

    • IOC容器关闭

    FactoryBean

    ①简介

    FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都屏蔽起来,只把最简洁的使用界面展示给我们。

    将来我们整合Mybatis时,Spring就是通过FactoryBean机制来帮我们创建SqlSessionFactory对象的

    ①创建类UserFactoryBean

    public class UserFactoryBean implements FactoryBean<User> {
        @Override
        public User getObject() throws Exception {
            return new User();
        }
    
        @Override
        public Class<?> getObjectType() {
            return User.class;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    ②配置bean

    <bean id="user" class="com.test.UserFactoryBean">bean>
    
    • 1

    ③测试

    @Test
    public void testUserFactoryBean(){
        //获取IOC容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-factorybean.xml");
        User user = (User) ac.getBean("user");
        System.out.println(user);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    基于xml自动装配

    自动装配:

    根据指定的策略,在IOC容器中匹配某一个bean,自动为指定的bean中所依赖的类类型或接口类型属性赋值

    ①场景模拟
    创建类UserController

    public class UserController {
    
        private UserService userService;
    
        public void setUserService(UserService userService) {
            this.userService = userService;
        }
    
        public void saveUser(){
            userService.saveUser();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    创建接口UserService

    public interface UserService {
    
        void saveUser();
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    创建类UserServiceImpl实现接口UserService

    public class UserServiceImpl implements UserService {
    
        private UserDao userDao;
    
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
    
        @Override
        public void saveUser() {
            userDao.saveUser();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    创建接口UserDao

    public interface UserDao {
    
        void saveUser();
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    创建类UserDaoImpl实现接口UserDao

    public class UserDaoImpl implements UserDao {
    
        @Override
        public void saveUser() {
            System.out.println("保存成功");
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    ②配置bean

    使用bean标签的autowire属性设置自动装配效果

    自动装配方式:byType

    byType:根据类型匹配IOC容器中的某个兼容类型的bean,为属性自动赋值

    若在IOC中,没有任何一个兼容类型的bean能够为属性赋值,则该属性不装配,即值为默认值null

    若在IOC中,有多个兼容类型的bean能够为属性赋值,则抛出异常NoUniqueBeanDefinitionException

    <bean id="userController" class="com.atguigu.test.controller.UserController" autowire="byType">bean>
    
    <bean id="userService" class="com.test.service.impl.UserServiceImpl" autowire="byType">bean>
    
    <bean id="userDao" class="com.test.dao.impl.UserDaoImpl">bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    自动装配方式:byName

    byName:将自动装配的属性的属性名,作为bean的id在IOC容器中匹配相对应的bean进行赋值

    <bean id="userController" class="com.test.controller.UserController" autowire="byName">bean>
    
    <bean id="userService" class="com.test.service.impl.UserServiceImpl" autowire="byName">bean>
    <bean id="userServiceImpl" class="com.test.service.impl.UserServiceImpl" autowire="byName">bean>
    
    <bean id="userDao" class="com.test.dao.impl.UserDaoImpl">bean>
    <bean id="userDaoImpl" class="com.test.dao.impl.UserDaoImpl">bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    ③测试

    @Test
    public void testAutoWireByXML(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("autowire-xml.xml");
        UserController userController = ac.getBean(UserController.class);
        userController.saveUser();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 相关阅读:
    买卖股票的最佳时机含冷冻期
    【Linux】安装配置虚拟机及虚拟机操作系统的安装
    jeecg 重新加载表格
    这个Spring Security登录插件牛啊,验证码、小程序、OAuth2都能快速接入
    关于 Qt串口不同电脑出现不同串口号打开失败 的解决方法
    17-数据结构-查找-(顺序、折半、分块)
    多层感知机学习XOR实例
    哆啦a梦教你页面的转发与重定向
    idea 打 jar 包以及运行使用
    关于 LLM 和知识图谱、图数据库,大家都关注哪些问题呢?
  • 原文地址:https://blog.csdn.net/Don_t_always_ail/article/details/133799562