Spring(上)
  y9EYnC7aLifI 2023年12月10日 19 0

1. Spring简介

Spring官网

Spring 是轻量级的框架,其基础版本只有 2 MB 左右的大小。

Spring 框架的核心特性是可以用于开发任何 Java 应用程序,但是在 Java EE 平台上构建 web 应 用程序是需要扩展的。

Spring 框架的目标是使 J2EE 开发变得更容易使用,通过启用基于 POJO 编程模型来促进良好的编程实践。

1.1 Spring 概述

Spring是一个开源的Java框架,它提供了全面的支持企业应用程序开发,包括面向切面编程、声明式事务管理、AOP、持久化框架(如JPA和Hibernate)、安全、Web MVC框架(如Spring MVC和JSF)以及许多其他功能。

Spring的主要目标是解决企业级应用程序开发中的复杂问题和提供更好的开发效率。它提供了各种模块和组件,可以用于构建各种规模的应用程序,包括微服务。

Spring的核心思想是依赖反转原则,它允许您将对象之间的依赖关系抽象化,并通过依赖注入的方式将它们传递给对象。

1.2 Spring家族

项目列表:https://spring.io/projects

1.3 Spring Framework

Spring 基础框架,可以视为 Spring 基础设施,基本上任何其他 Spring 项目都是以 Spring Framework 为基础的。

1.Spring Framework特性

  • 非侵入式:使用 Spring Framework 开发应用程序时,Spring 对应用程序本身的结构影响非常小。对领域模型可以做到零污染;对功能性组件也只需要使用几个简单的注解进行标记,完全不会破坏原有结构,反而能将组件结构进一步简化。这就使得基于 Spring Framework 开发应用程序 时结构清晰、简洁优雅。
  • 控制反转:IOC——Inversion of Control,翻转资源获取方向。把自己创建资源、向环境索取资源 变成环境将资源准备好,我们享受资源注入。
  • 面向切面编程:AOP——Aspect Oriented Programming,在不修改源代码的基础上增强代码功能。
  • 容器:Spring IOC 是一个容器,因为它包含并且管理组件对象的生命周期。组件享受到了容器化的管理,替程序员屏蔽了组件创建过程中的大量细节,极大的降低了使用门槛,大幅度提高了开发效率。
  • 组件化:Spring 实现了使用简单的组件配置组合成一个复杂的应用。在 Spring 中可以使用 XML 和 Java 注解组合这些对象。这使得我们可以基于一个个功能明确、边界清晰的组件有条不紊的搭 建超大型复杂应用系统。
  • 声明式:很多以前需要编写代码才能实现的功能,现在只需要声明需求即可由框架代为实现。
  • 一站式:在 IOC 和 AOP 的基础上可以整合各种企业应用的开源框架和优秀的第三方类库。而且 Spring 旗下的项目已经覆盖了广泛领域,很多方面的功能性需求可以在 Spring Framework 的基 础上全部使用 Spring 来实现。

2.Spring Framework五大功能模块

功能模块 功能介绍
Core Container 核心容器,在 Spring 环境下使用任何功能都必须基于 IOC 容器。
AOP&Aspects 面向切面编程
Testing 提供了对 junit 或 TestNG 测试框架的整合。
Data Access/Integration 提供了对数据访问/集成的功能。
Spring MVC 提供了面向Web应用程序的集成功能。

2. IOC

2.1 IOC容器

1. IOC思想

IOC:Inversion of Control,控制反转

获取资源的传统方式

在应用程序中的组件需要获取资源时,传统的方式是组件主动的从容器中获取所需要的资源,在这样的模式下开发人员往往需要知道在具体容器中特定资源的获取方式,增加了学习成本,同时降低了开发效率。

反转控制方式获取资源

反转控制的思想完全颠覆了应用程序组件获取资源的传统方式:反转了资源的获取方向——改由容器主动的将资源推送给需要的组件,开发人员不需要知道容器是如何创建资源对象的,只需要提供接收资源 的方式即可,极大的降低了学习成本,提高了开发的效率。这种行为也称为查找的被动形式

DI

Dependency Injection,依赖注入

DI 是 IOC 的另一种表述方式:即组件以一些预先定义好的方式(例如:setter 方法)接受来自于容器的资源注入。相对于IOC而言,这种表述更直接。

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

2.IOC容器在Spring中的实现

Spring 的 IOC 容器就是 IOC 思想的一个落地的产品实现。IOC 容器中管理的组件也叫做 bean。在创建 bean 之前,首先需要创建 IOC 容器。

Spring 提供了 IOC 容器的两种实现方式:

BeanFactory

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

ApplicationContext

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

ApplicationContext的主要实现类

<img src="https://gitee.com/Lowell_37/picgoImg/raw/master/202310192045095.png" alt="image-20231019204520981" style="zoom: 33%;" />

202310192045095

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

2.2 基于XML管理bean

1. Hello, Spring

创建Maven Module
引入依赖
<dependencies>
    <!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.1</version>
    </dependency>

    <!-- junit测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<img src="https://gitee.com/Lowell_37/picgoImg/raw/master/202310260934125.png" alt="image-20231026093418927" style="zoom:50%;" />

创建类HelloWorld
public class HelloWorld {
    public void sayHello() {
        System.out.println("Hello, Spring!");
    }
}
创建Spring的配置文件

<img src="https://gitee.com/Lowell_37/picgoImg/raw/master/202310260937196.png" alt="image-20231026093716055" style="zoom:50%;" />

在Spring的配置文件中配置bean
<!--
配置HelloWorld所对应的bean,即将HelloWorld的对象交给Spring的IOC容器管理
通过bean标签配置IOC容器所管理的bean
属性:
id:设置bean的唯一标识
class:设置bean所对应类型的全类名
-->
<bean id="helloworld" class="com.lowell.spring.bean.HelloWorld"></bean>
创建测试类测试
public class HelloWorldTest {
    @Test
    public void test() {
        // 获取IOC容器
        ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 获取IOC容器中的bean
        HelloWorld helloWorld = (HelloWorld) ioc.getBean("helloworld");
        helloWorld.sayHello();
    }
}
思路

<img src="C:/Users/86131/AppData/Roaming/Typora/typora-user-images/image-20231026094100970.png" alt="image-20231026094100970" style="zoom:50%;" />

注意:Spring 底层默认通过反射技术调用组件类的无参构造器来创建组件对象,这一点需要注意。如果在需要无参构造器时,没有无参构造器,则会抛出下面的异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'helloworld' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.atguigu.spring.bean.HelloWorld]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.atguigu.spring.bean.HelloWorld. ()

2.获取bean

方式一:根据id获取

由于 id 属性指定了 bean 的唯一标识,所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。 上述Hello, Spring 中我们使用的就是这种方式

方式二:根据类型获取
@Test
public void testHelloWorld(){
ApplicationContext ac = new
ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld bean = ac.getBean(HelloWorld.class);
bean.sayHello();
}
方式三:根据id和类型
@Test
public void testHelloWorld(){
ApplicationContext ac = new
ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld bean = ac.getBean("helloworld", HelloWorld.class);
bean.sayHello();
}
注意

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

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

<bean id="helloworldOne" class="com.atguigu.spring.bean.HelloWorld"></bean>
<bean id="helloworldTwo" class="com.atguigu.spring.bean.HelloWorld"></bean>

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

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.atguigu.spring.bean.HelloWorld' available: expected single matching bean but found 2: helloworldOne,helloworldTwo
扩展

如果组件类实现了接口,根据接口类型可以获取 bean ,,前提是bean唯一

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

结论

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

3.依赖注入之setter注入

①创建学生类Student
public class Student{
    private Integer sid;
    private String sname;
    private Integer age;
    private String gender;

    public Student() {
    }


    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", age=" + age +
                ", gender='" + gender
    }
}
②在spring-ioc.xml中配置bean时为属性赋值
<bean id="studentTwo" class="com.lowell.spring.pojo.Student">
    <!--通过setter注入为成员变量赋值-->
    <!--
        property:通过成员变量的set方法进行赋值
        name:设置需要赋值的属性名,和成员变量没有关系
        value:设置为属性所赋的值
    -->
    <property name="sid" value="1001"/>
    <property name="sname" value="张三"/>
    <property name="age" value="23"/>
    <property name="gender" value="男"/>
</bean>
③测试
@Test
    public void testDI1() {
        // 获取IOC容器
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
        // 获取bean
        Student student = ioc.getBean("studentTwo", Student.class);
        System.out.println(student);

    }

测试结果:

student = Student{sid=1001, sname='张三', age=23, gender='男'}

4.依赖注入之构造器注入

①在Student类中添加有参构造
public Student(Integer sid, String sname,  String gender) {
    this.sid = sid;
    this.sname = sname;
    this.gender = gender;
}
②配置bean
<bean id="studentThree" class="com.lowell.spring.pojo.Student">
    <!--通过构造器注入-->
    <constructor-arg value="1002"/>
    <constructor-arg value="林娜"/>
    <constructor-arg value="女"/>
    <constructor-arg value="50" name="age"/>
</bean>
constructor-arg标签还有两个属性可以进一步描述构造器参数:
index属性:指定参数所在位置的索引(从0开始)
name属性:指定参数名
③测试
@Test
public void testIOC() {
    // 获取IOC容器
    ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
    // 获取bean
    Student student = ioc.getBean("studentThree", Student.class);
    System.out.println("student = " + student);
}

测试结果:

student = Student{sid=1002, sname='林娜', age=50, gender='女'}

5.特殊值处理

①字面量赋值

什么是字面量?

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

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

<!-- 使用value属性给bean的属性赋值时,Spring会把value属性的值看做字面量 -->
<property name="name" value="张三"/>
②null值
<property name="name">
	<null />
</property>
<!--以下写法,为name所赋的值是字符串null-->
<property name="name" value="null"></property>
③xml实体
<!-- 小于号在XML文档中用来定义标签的开始,不能随便使用 -->
<!-- 解决方案一:使用XML实体来代替 -->
<property name="expression" value="a &lt; b"/>
④CDATA节
<property name="expression">
<!-- 解决方案二:使用CDATA节 -->
<!-- CDATA中的C代表Character,是文本、字符的含义,CDATA就表示纯文本数据 -->
<!-- XML解析器看到CDATA节就知道这里是纯文本,就不会当作XML标签或属性来解析 -->
<!-- 所以CDATA节中写什么符号都随意 -->
<value><![CDATA[a < b]]></value>
</property>
测试
<bean id="studentFour" class="com.lowell.spring.pojo.Student">
    <property name="sid" value="1003"/>
    <!--
        <: &lt;
        >: &gt;
        CDATA节其中的内容会原样解析<![CDATA[...]]>
        CDATA节是xml中一个特殊的标签,因此不能写在一个属性中
    -->
    <!--<property name="sname" value="&lt;王五&gt;"/>-->
    <property name="sname">
        <value><![CDATA[<王五>]]></value>
    </property>
    <property name="gender">
        <null/>
    </property>
</bean>

测试结果:

Student{sid=1003, sname='<王五>', age=null, gender='null'}

6.为类类型属性赋值

①创建班级类Clazz
public class Clazz {
    private Integer cid;
    private String cname;
    public Clazz() {
    }

    public Clazz(Integer cid, String cname) {
        this.cid = cid;
        this.cname = cname;
    }

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }


    @Override
    public String toString() {
        return "Clazz{" +
                "cid=" + cid +
                ", cname='" + cname ;
    }
}
②修改Student

Student类中添加以下代码:

private Clazz clazz;
public Clazz getClazz() {
	return clazz;
}
public void setClazz(Clazz clazz) {
	this.clazz = clazz;
}
③方式一:引用外部已声明的bean

配置Clazz类型的bean:

<bean id="clazzOne" class="com.lowell.spring.pojo.Clazz">
        <property name="cid" value="1111"/>
        <property name="cname" value="bestClazz"/>
</bean>

Student中的clazz属性赋值:

<bean id="studentFive" class="com.lowell.spring.pojo.Student">
    <property name="sid" value="1004"/>
    <property name="sname" value="赵六"/>
    <property name="age" value="26"/>
    <property name="gender" value="男"/>
    <!--ref:引用当前IOC容器中的某一个bean的id,将所对应的bean为属性赋值-->
    <property name="clazz" ref="clazzOne"/>
</bean>

错误演示:

<bean id="studentFive" class="com.lowell.spring.pojo.Student">
    <property name="sid" value="1004"/>
    <property name="sname" value="赵六"/>
    <property name="age" value="26"/>
    <property name="gender" value="男"/>
    <!--ref:引用当前IOC容器中的某一个bean的id,将所对应的bean为属性赋值-->
    <property name="clazz" value="clazzOne"/>
</bean>

如果错把ref属性写成了value属性,会抛出异常: Caused by: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.atguigu.spring.bean.Clazz' for property 'clazz': no matching editors or conversion strategy found

意思是不能把String类型转换成我们要的Clazz类型,说明我们使用value属性时,Spring只把这个 属性看做一个普通的字符串,不会认为这是一个bean的id,更不会根据它去找到bean来赋值

测试:

@Test
public void testDI4() {
    /*
    * 引用外部的bean
    */
    // 获取IOC容器
    ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
    // 获取bean
    Student student = ioc.getBean("studentFive", Student.class);
    System.out.println(student);

}

测试结果:

Student{sid=1004, sname='赵六', age=26, gender='男', clazz=Clazz{cid=1111, cname='bestClazz'}
④方式二:内部bean
<bean id="studentFive" class="com.lowell.spring.pojo.Student">
    <property name="sid" value="1004"/>
    <property name="sname" value="赵六"/>
    <property name="age" value="26"/>
    <property name="gender" value="男"/>

    <property name="clazz">
        <!-- 在一个bean中再声明一个bean就是内部bean -->
        <!--内部bean,只能在当前bean的内部使用,不能直接通过IOC容器获取,因此可以省略id属性 -->
        <bean id="clazzInner" class="com.lowell.spring.pojo.Clazz">
            <property name="cid" value="2222"/>
            <property name="cname" value="远大前程班"/>
        </bean>
    </property>
</bean>

测试结果:

Student{sid=1004, sname='赵六', age=26, gender='男', clazz=Clazz{cid=2222, cname='远大前程班'}
⑤方式三:级联属性赋值
<bean id="studentFive" class="com.lowell.spring.pojo.Student">
    <property name="sid" value="1004"/>
    <property name="sname" value="Leo"/>
    <property name="age" value="28"/>
    <property name="gender" value="男"/>
	<!-- 一定先引用某个bean为属性赋值,才可以使用级联方式更新属性 -->
    <property name="clazz" ref="clazzOne"/>
    <!--级联的方式:要保证提前为clazz属性赋值或者实例化-->
    <property name="clazz.cid" value="2222"/>
    <property name="clazz.cname" value="远大前程班"/>
</bean>

测试:

@Test
public void testDI5() {
    // 获取IOC容器
    ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
    // 获取bean
    Clazz clazz = ioc.getBean("clazzOne", Clazz.class);
    System.out.println("clazz = " + clazz);
}

测试结果:

clazz = Clazz{cid=2222, cname='最强王者班'}

7.为数组类型属性赋值

①修改Student类

在Student类中添加以下代码:

private String[] hobbies;
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(String[] hobbies) {
	this.hobbies = hobbies;
}
②配置bean
<bean id="studentFive" class="com.lowell.spring.pojo.Student">
    <property name="sid" value="1004"/>
    <property name="sname" value="Leo"/>
    <property name="age" value="28"/>
    <property name="gender" value="男"/>
    <!--ref:引用当前IOC容器中的某一个bean的id-->
    <property name="clazz" ref="clazzOne"/>
    <property name="hobby">
        <array>
            <value>Eating</value>
            <value>Playing</value>
            <value>Sleeping</value>
        </array>
    </property>
</bean>
③测试结果
Student{sid=1004, sname='Leo', age=28, gender='男',clazz=Clazz{cid=1111, cname='bestClazz', hobby=[Eating, Playing, Sleeping]}}

8.为集合类型属性赋值

①为List集合类型属性赋值

在Clazz类中添加以下代码:

private List<Student> students;
public List<Student> getStudents() {
	return students;
}
public void setStudents(List<Student> students) {
	this.students = students;
}

配置bean:

<bean id="clazzOne" class="com.lowell.spring.pojo.Clazz">
    <property name="cid" value="1111"/>
    <property name="cname" value="bestClazz"/>
    <property name="students" ref="studentList"/>
    <property name="students">
        <list>
            <ref bean="studentOne"/>
            <ref bean="studentTwo"/>
            <ref bean="studentThree"/>
        </list>
    </property>
</bean>

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

测试

clazz = Clazz{cid=1111, cname='bestClazz', students=[Student{sid=null, sname='null', age=null, gender='null', clazz=null, hobby=null,}, Student{sid=1001, sname='张三', age=23, gender='男', clazz=null, hobby=null,}, Student{sid=1002, sname='林娜', age=50, gender='女', clazz=null, hobby=null}]}

②为Map集合类型属性赋值

创建教师类Teacher:

public class Teacher {
    private Integer tid;
    private String tname;

    public Teacher() {
    }

    public Teacher(Integer tid, String tname) {
        this.tid = tid;
        this.tname = tname;
    }

    public Integer getTid() {
        return tid;
    }

    public void setTid(Integer tid) {
        this.tid = tid;
    }
    public String getTname() {
        return tname;
    }
    public void setTname(String tname) {
        this.tname = tname;
    }
    @Override
    public String toString() {
        return "Teacher{" +
                "tid=" + tid +
                ", tname='" + tname + '\'' +
                '}';
    }
}

在Student类中添加以下代码:

private Map<String, Teacher> teacherMap;
public Map<String, Teacher> getTeacherMap() {
	return teacherMap;
}
public void setTeacherMap(Map<String, Teacher> teacherMap) {
	this.teacherMap = teacherMap;
}

配置bean:

<bean id="teacherOne" class="com.lowell.spring.pojo.Teacher">
    <property name="tid" value="10086"/>
    <property name="tname" value="大宝"/>
</bean>

<bean id="teacherTwo" class="com.lowell.spring.pojo.Teacher">
    <property name="tid" value="10010"/>
    <property name="tname" value="小宝"/>
</bean>

<bean id="studentFive" class="com.lowell.spring.pojo.Student">
        <property name="sid" value="1004"/>
        <property name="sname" value="Leo"/>
        <property name="age" value="28"/>
        <property name="gender" value="男"/>

        <!--ref:引用当前IOC容器中的某一个bean的id-->
        <property name="clazz" ref="clazzOne"/>
        <property name="hobby">
            <array>
                <value>Eating</value>
                <value>Playing</value>
                <value>Sleeping</value>
            </array>
        </property>
        <property name="teacherMap">
            <map>
                <!--一个entry代表一个键值对-->
                <entry key="10086" value-ref="teacherOne"/>
                <entry key="10010" value-ref="teacherTwo"/>
            </map>
        </property>
    </bean>

测试结果:

Student{sid=1004, sname='Leo', age=28, gender='男', score=null, clazz=Clazz{cid=1111, cname='bestClazz', students=[Student{sid=null, sname='null', age=null, gender='null', score=null, clazz=null, hobby=null, teacherMap=null}, Student{sid=1001, sname='张三', age=23, gender='男', score=null, clazz=null, hobby=null, teacherMap=null}, Student{sid=1002, sname='林娜', age=50, gender='女', score=null, clazz=null, hobby=null, teacherMap=null}]}, hobby=[Eating, Playing, Sleeping], teacherMap={10086=Teacher{tid=10086, tname='大宝'}, 10010=Teacher{tid=10010, tname='小宝'}}}
③引用集合类型的bean
<!--配置一个集合类型的bean,需要使用util的约束-->
    <util:list id="studentList">
        <ref bean="studentOne"/>
        <ref bean="studentTwo"/>
        <ref bean="studentThree"/>
    </util:list>

    <util:map id="teacherMap">
        <entry key="10086" value-ref="teacherOne"/>
        <entry key="10010" value-ref="teacherTwo"/>
    </util:map>

<bean id="studentFive" class="com.lowell.spring.pojo.Student">
        <property name="sid" value="1004"/>
        <property name="sname" value="Leo"/>
        <property name="age" value="28"/>
        <property name="gender" value="男"/>

        <!--ref:引用当前IOC容器中的某一个bean的id-->
        <property name="clazz" ref="clazzOne"/>
        <property name="hobby">
            <array>
                <value>Eating</value>
                <value>Playing</value>
                <value>Sleeping</value>
            </array>
        </property>
        <property name="teacherMap" ref="teacherMap"/>
    </bean>
    <bean id="clazzOne" class="com.lowell.spring.pojo.Clazz">
        <property name="cid" value="1111"/>
        <property name="cname" value="bestClazz"/>
        <property name="students" ref="studentList"/>
</bean>

9. p命名空间

引入p命名空间后,可以通过以下方式为bean的各个属性赋值

<!--p命名空间-->
<bean id="studentSix" class="com.lowell.spring.pojo.Student"
      p:sid="1005" p:sname="小明" p:teacherMap-ref="teacherMap"/>

测试

Student{sid=1005, sname='小明', age=null, gender='null', score=null, clazz=null, hobby=null, teacherMap={10086=Teacher{tid=10086, tname='大宝'}, 10010=Teacher{tid=10010, tname='小宝'}}}

10. 引入外部属性文件

① 加入依赖
<!-- MySQL驱动 -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.7.29</version>
</dependency>
<!-- 数据源 -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.0.31</version>
</dependency>

②创建外部属性文件jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterencoding=utf-8
jdbc.username=root
jdbc.password=******
③引入属性文件
<!-- 引入外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
④配置bean
<!--IOC容器管理数据源-->
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${jdbc.driver}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
⑤测试
@Test
public void testDataSource() throws SQLException {
    ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-datasource.xml");
    DruidDataSource dataSource = ioc.getBean(DruidDataSource.class);
    System.out.println(dataSource.getConnection());
}
com.mysql.jdbc.JDBC4Connection@737a135b

11.bean的作用域

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

取值 含义 创建对象时期
singleton(默认) 在IOC容器中,这个bean的对象始终为单实例 IOC容器初始化时
prototype 这个bean在IOC容器中有多个实例 获取bean时
①创建类User
②配置bean
<!--
    scope:设置bean的作用域
    scope="singleton | prototype"
    singleton(单例):表示获取该bean所对应的对象都是同一个
    prototype(多例):表示获取该bean所对应的对象都不是同一个
-->
<bean id="student"  class="com.lowell.spring.pojo.Student" scope="prototype">
    <property name="sid" value="1001"/>
    <property name="sname" value="张三"/>
</bean>
③测试
@Test
public void testScope() {
    ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-scope.xml");
    Student student1 = ioc.getBean(Student.class);
    Student student2 = ioc.getBean(Student.class);
    System.out.println(student1==student2);
}

12. bean的生命周期

①具体的生命周期过程
  • bean对象创建(调用无参构造器)
  • 给bean对象设置属性
  • bean对象初始化之前操作(由bean的后置处理器负责)
  • bean对象初始化(需在配置bean时指定初始化方法)
  • bean对象初始化之后操作(由bean的后置处理器负责)
  • bean对象就绪可以使用
  • bean对象销毁(需在配置bean时指定销毁方法)
  • IOC容器关闭
②修改类User
public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer age;

    public User() {
        System.out.println("生命周期:1、初始化");
    }
    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) {
        System.out.println("生命周期:2、依赖注入");
        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;
    }

    public void initMethod(){
        System.out.println("生命周期:3、初始化");
    }

    public void destroyMethod(){
        System.out.println("生命周期:5、销毁");
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}
③配置bean
<!-- 使用init-method属性指定初始化方法 -->
<!-- 使用destroy-method属性指定销毁方法 -->
<bean class="com.atguigu.bean.User" scope="prototype" init-method="initMethod"
destroy-method="destroyMethod">
	<property name="id" value="1001"></property>
	<property name="username" value="admin"></property>
	<property name="password" value="123456"></property>
	<property name="age" value="23"></property>
</bean>
④测试
@Test
public void test() {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
    User bean = ac.getBean(User.class);
    System.out.println("生命周期:4、通过IOC容器获取bean并使用");
    ac.close();
}
生命周期:1、初始化
生命周期:2、依赖注入
生命周期:3、初始化
生命周期:4、通过IOC容器获取bean并使用
生命周期:5、销毁
⑤bean的后置处理器

bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口, 且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容 器中所有bean都会执行

创建bean的后置处理器:

package com.lowell.spring.process;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * @Date:2023/10/20 19:36
 * @Author:Lowell
 * @Description:
 **/
public class MyBeanPostProcess implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 此方法在bean的生命周期初始化之前执行
        System.out.println("MyBeanPostProcess-->后置处理器postProcessBeforeInitialization");
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 此方法在bean的生命周期初始化之后执行
        System.out.println("MyBeanPostProcess-->后置处理器postProcessAfterInitialization");
        return bean;
    }
}

在IOC容器中配置后置处理器:

<!-- bean的后置处理器要放入IOC容器才能生效 -->
<bean id="myBeanPostProcess" class="com.lowell.spring.process.MyBeanPostProcess"/>

1、实例化 2、依赖注入 3、后置处理器的postProcessBeforeInitialization 4、初始化,需要通过bean的init-method属性指定初始化的方法 5、后置处理器的postProcessAfterInitialization 6、IOC容器关闭时的销毁,需要通过bean的destroy-method属性指定销毁的方法 当bean的作用域设置为多例时,destroy()方法便不由IOC容器管理 bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口, 且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容 器中所有bean都会执行

注意: 1、若bean的作用域为单例时,生命周期的前三个步骤会在获取IOC容器时执行 2、若bean的作用域为多例时,生命周期的前三个步骤会在获取bean时执行

测试

@Test
public void test() {
    // ConfigurableApplicationContext是ApplicationContext的子接口,其中扩展了刷新和关闭容器的方法
    ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
    User user = ioc.getBean(User.class);
    System.out.println("user = " + user);
    ioc.close();
}
生命周期:1、初始化
生命周期:2、依赖注入
MyBeanPostProcess-->后置处理器postProcessBeforeInitialization
生命周期:3、初始化
MyBeanPostProcess-->后置处理器postProcessAfterInitialization
user = User{id=1, username='admin', password='123456', age=23}
生命周期:5、销毁

13. FactoryBean

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

①创建类UserFactoryBean
public class UserFactoryBean implements FactoryBean<User> {
    @Override
    public User getObject() throws Exception {
        return new User();
    }

    @Override
    public Class<?> getObjectType() {
        return User.class;
    }
}
②配置bean
<bean class="com.lowell.spring.factory.UserFactoryBean"/>
③测试
/**
 * @Date:2023/10/20 19:52
 * @Author:Lowell
 * @Description:
 * FactoryBean是一个接口,需要创建一个类实现该接口
 * 其中有三个方法:
 * 1、getObject():通过一个对象交给IOC容器管理
 * 2、getObjectType():所提供的对象是否是单例
 * 当把FactoryBean的实现类配置为Bean时,会将当前类中的getObject()所返回的对象交给IOC容器管理
 **/
public class FactoryBeanTest {
    @Test
    public void testFactoryBean() {
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-factory.xml");
        User user = ioc.getBean(User.class);
        System.out.println(user);
    }

}
生命周期:1、初始化
User{id=null, username='null', password='null', age=null}

14. 基于xml的自动装配

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

①场景模拟

创建类UserController

public class UserController {
    private UserService userService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void saveUser() {
        userService.saveUser();
    }
}

创建接口UserService

public interface UserService {
    /**
     * 保存用户信息
     */
    void saveUser();
}

创建类UserServiceImpl实现接口UserService

public class UserServiceImpl implements UserService {

    private UserDao userDao;

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void saveUser() {
        userDao.saveUser();
    }
}

创建接口UserDao

public interface UserDao {
    /**
     * 保存用户信息
     */
    void saveUser();
}

创建类UserDaoImpl实现接口UserDao

public class UserDaoImpl implements UserDao {
    @Override
    public void saveUser() {
        System.out.println("保存成功");
    }
}
②配置bean

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

自动装配方式:byType

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

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

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

<bean id="userController"
class="com.lowell.controller.UserController" autowire="byType">
</bean>
<bean id="userService"
class="com.lowell.service.impl.UserServiceImpl" autowire="byType">
</bean>
<bean id="userDao" class="com.lowell.dao.impl.UserDaoImpl"></bean>

自动装配方式:byName

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

<bean id="userController" class="com.lowell.spring.controller.UserController" autowire="byName"/>

<bean id="userService" class="com.lowell.spring.service.impl.UserServiceImpl" autowire="byName"/>

<bean id="service" class="com.lowell.spring.service.impl.UserServiceImpl" autowire="byName"/>

<bean id="userDao" class="com.lowell.spring.dao.impl.UserDaoImpl"/>

<bean id="dao" class="com.lowell.spring.dao.impl.UserDaoImpl"/>
③测试
public class AutoWireByXMLTest {
    /**
     * 自动装配:
     * 根据指定的策略,在IOC容器中匹配某个bean,自动为bean中的类类型的属性或者接口类型的属性赋值
     * 可通过bean标签中的autowire属性设置自动装配的策略
     * 自动装配的策略:
     * no, default:表示不装配,即bean中的属性不会自动装配某个bean为属性赋值,此时属性使用默认值
     * byType:根据要赋值的属性的类型,在IOC容器中匹配某个bean为属性赋值
     *
     * 注意:
     * 1、若通过类型没有找到任何一个类型匹配的bean,此时不装配,属性使用默认值
     * 2、若同通过类型找到了多个类型匹配的bean,此时抛出异常,NoUniqueBeanDefinitionException
     * 总结:当使用byType实现自动装配时,IOC容器中有且只有一个类型匹配的bean能够为属性赋值
     * 3、byName:将要赋值的属性的属性名作为bean的id,在IOC容器中匹配某个bean,为属性赋值
     * 总结:当类型匹配的bean有多个时,此时可以使用byName实现自动装配
     */

    @Test
    public void testAutoWire() {
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-autowire-xml.xml");
        UserController userController = ioc.getBean(UserController.class);
        userController.saveUser();
    }
}
保存成功

2.3 基于注解管理bean

1. 标记与扫描

注解

和 XML 配置文件一样,注解本身并不能执行,注解本身仅仅只是做一个标记,具体的功能是框架检测 到注解标记的位置,然后针对这个位置按照注解标记的功能来执行具体操作。

本质上:所有一切的操作都是Java代码来完成的,XML和注解只是告诉框架中的Java代码如何执行。

扫描

Spring 为了知道程序员在哪些地方标记了什么注解,就需要通过扫描的方式,来进行检测。然后根据注 解进行后续操作。

①新建Maven Module,导入依赖
<!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.1</version>
</dependency>

<!-- junit测试 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
②创建Spring配置文件
③创建组件
@Component:将类标识为普通组件 

@Controller:将类标识为控制层组件 

@Service:将类标识为业务层组件 

@Repository:将类标识为持久层组件

创建控制层组件

@Controller
public class UserController {}

创建接口UserService

public interface UserService {}

创建业务层组件UserServiceImpl

@Service
public class UserServiceImpl implements UserService {}

创建接口UserDao

public interface UserDao {}

创建持久层组件UserDaoImpl

@Repository
public class UserDaoImpl implements UserDao {}
④扫描组件

最基本的扫描方式

<!--扫描组件-->
<context:component-scan base-package="com.lowell.spring"/>

指定要排除的组件

<context:component-scan base-package="com.lowell">
<!--
context:exclude-filter:排除扫描
    type:设置排除扫描得方式
    type="annotation | assignable"
    annotation:根据注解的类型进行排除,expression需要设置排除的注解的全类名
    assignable:根据类的类型进行排除,expression需要设置排除的类的全类名
-->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<!--<context:exclude-filter type="assignable"
expression="com.lowell.controller.UserController"/>-->
</context:component-scan>

仅扫描指定组件

<!--
    context:include-filter:包含扫描
    注意:需要在context:component-scan标签中设置use-default-filters="false"
    use-default-filters="true":所设置的包下所有的类都要扫描,此时可以使用排除扫描
    use-default-filters="false",所设置的包下所有的类都不需要扫描,此时可以使用包含扫描
-->
 <context:component-scan base-package="com.lowell.spring" use-default-filters="false">
        <!--<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
        <context:include-filter type="assignable" expression="com.lowell.spring.controller.UserController"/>
    </context:component-scan>
⑤测试
    public void testIOCByAnnotation() {
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc-annotation.xml");
        UserController userController = ioc.getBean("userController",UserController.class);
        System.out.println(userController);

        UserService userService = ioc.getBean("userServiceImpl", UserService.class);
        System.out.println("userService = " + userService);

        UserDao userDao = ioc.getBean("userDaoImpl", UserDao.class);
        System.out.println("userDao = " + userDao);
    }

在我们使用XML方式管理bean的时候,每个bean都有一个唯一标识,便于在其他地方引用。现在使用注解后,每个组件仍然应该有一个唯一标识。

默认情况

类名首字母小写就是bean的id。

例如:UserController类对应的bean的id就是userController

自定义bean的id可通过标识组件的注解的value属性设置自定义的bean的id

@Service("userService") //默认为userServiceImpl

public class UserServiceImpl implements UserService {}

2.基于注解的自动装配

@Autowired

在成员变量上直接标记@Autowired注解即可完成自动装配,不需要提供setXxx()方法。

如下:

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    public void saveUser() {
        userService.saveUser();
    }
}

创建以下接口与函数:

public interface UserDao {
    // 保存用户信息
    void saveUser();
}
@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void saveUser() {
        System.out.println("保存成功!");
    }
}
public interface UserService {
    // 保存用户信息
    void saveUser();
}
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public void saveUser() {
        userDao.saveUser();
    }
}

@Autowired注解可以标记在构造器和set方法上

@Autowired工作流程

<img src="https://gitee.com/Lowell_37/picgoImg/raw/master/202311061632499.png" alt="image-20231106163156143" style="zoom:33%;" />

首先根据所需要的组件类型到IOC容器中查找

  • 能够找到唯一的bean:直接执行装配
  • 如果完全找不到匹配这个类型的bean:装配失败
  • 和所需类型匹配的bean不止一个
    • 没有@Qualifier注解:根据@Autowired标记位置成员变量的变量名作为bean的id进行 匹配
      • 能够找到:执行装配
      • 找不到:装配失败
    • 使用@Qualifier注解:根据@Qualifier注解中指定的名称作为bean的id进行匹配
      • 能够找到:执行装配
      • 找不到:装配失败

如下:

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    @Qualifier("userDaoImpl")
    private UserDao userDao;
    @Override
    public void saveUser() {
        userDao.saveUser();
    }
}
@Autowired注解原理
  • 默认通过byType的方式,在IOC容器中通过类型匹配某个bean为属性赋值

  • 若有多个类型匹配的bean,此时会自动转换为byName的方式实现自动装配的效果,即,将要赋值的属性的属性名作为bean的id匹配某一个bean为属性赋值

  • 若byType和byName都无法实现自动装配,即IOC容器中有多个类型匹配的bean,且这些bean的id和要赋值的属性的属性名都不一致,此时抛出异常:NoUniqueBeanDefinitionException,此时可以在要赋值的属性上,添加一个注解@Qualifier,通过该注解的value属性值,指定某个bean的id,将这个bean为属性赋值

    注意:若IOC容器中没有任何一个类型匹配的bean,此时抛出异常:NoSuchBeanDefinitionException

  • 在@Autowired注解中有个属性required,默认值为true,要求必须完成自动装配

  • 可以将required设置为false,此时能装配则装配,无法装配则使用属性默认值,但是实际开发时,基本上所有需要装配组件的地方都是必须装配的,用不上这个属性。

测试
@Test
    public void testIOCByAnnotation() {
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc-annotation.xml");
        UserController userController = ioc.getBean("userController",UserController.class);
        System.out.println(userController);

        UserService userService = ioc.getBean("userServiceImpl", UserService.class);
        System.out.println("userService = " + userService);

        UserDao userDao = ioc.getBean("userDaoImpl", UserDao.class);
        System.out.println("userDao = " + userDao);
        userController.saveUser();
    }
com.lowell.spring.controller.UserController@20d7d6fb
userService = com.lowell.spring.service.impl.UserServiceImpl@4ef782af
userDao = com.lowell.spring.dao.impl.UserDaoImpl@11d8ae8b
保存成功!

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月10日 0

暂无评论

推荐阅读
  2Vtxr3XfwhHq   2024年05月17日   46   0   0 Java
  8s1LUHPryisj   2024年05月17日   42   0   0 Java
  aRSRdgycpgWt   2024年05月17日   44   0   0 Java
y9EYnC7aLifI