2、IOC
2.1、IOC容器
2.1.1、IOC思想
IOC:Inversion of Control,翻译过来是反转控制。
①获取资源的传统方式
自己做饭:买菜、洗菜、择菜、改刀、炒菜,全过程参与,费时费力,必须清楚了解资源创建整个过程
中的全部细节且熟练掌握。
在应用程序中的组件需要获取资源时,传统的方式是组件主动的从容器中获取所需要的资源,在这样的
模式下开发人员往往需要知道在具体容器中特定资源的获取方式,增加了学习成本,同时降低了开发效
率。
②反转控制方式获取资源
点外卖:下单、等、吃,省时省力,不必关心资源创建过程的所有细节。
反转控制的思想完全颠覆了应用程序组件获取资源的传统方式:反转了资源的获取方向
——改由容器主
动的将资源推送给需要的组件,开发人员不需要知道容器是如何创建资源对象的,只需要提供接收资源
的方式即可,极大的降低了学习成本,提高了开发的效率。这种行为也称为查找的被动形式。
③DI
DI:Dependency Injection,翻译过来是依赖注入。
DI 是 IOC 的另一种表述方式:即组件以一些预先定义好的方式(例如:setter 方法)接受来自于容器
的资源注入。相对于IOC而言,这种表述更直接。
所以结论是:IOC 就是一种反转控制的思想, 而 DI 是对 IOC 的一种具体实现。
2.1.2、IOC容器在Spring中的实现
Spring 的 IOC 容器就是 IOC 思想的一个落地的产品实现。IOC 容器中管理的组件也叫做 bean。在创建
bean 之前,首先需要创建 IOC 容器。Spring 提供了 IOC 容器的两种实现方式:
①BeanFactory
这是 IOC 容器的基本实现,是 Spring 内部使用的接口。面向 Spring 本身,不提供给开发人员使用。
②ApplicationContext
BeanFactory 的子接口,提供了更多高级特性。面向 Spring 的使用者,几乎所有场合都使用
ApplicationContext 而不是底层的 BeanFactory。
③ApplicationContext的主要实现类
2.2、基于XML管理bean
2.2.1、实验一:入门案例
①创建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>
③创建类HelloWorld
public class HelloWorld {
public void sayHello(){
System.out.println("Hello,Spring!!");
}
}
④创建Spring的配置文件
⑤在Spring的配置文件中配置bean
<!--
配置HelloWorld所对应的bean,即将HelloWorld的对象交给Spring的IOC容器管理 通过bean标签配置IOC容器所管理的bean
属性:
id:设置bean的唯一标识
class:设置bean所对应类型的全类名
-->
<bean id="helloworld" class="com.atguigu.spring.bean.HelloWorld"></bean>
⑥创建测试类测试
@Test
public void test(){
//获取IOC容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取IOC容器中的bean对象
HelloWorld helloWorld = (HelloWorld) ioc.getBean("helloWorld");
helloWorld.sayHello();
}
⑦思路
⑧注意
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.2.2、实验二:获取bean
①方式一:根据id获取
由于 id 属性指定了 bean 的唯一标识,所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。
上个实验中我们使用的就是这种方式。
②方式二:根据类型获取
//获取IOC容器
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
//获取bean
Student studentOne = (Student) ioc.getBean("studentOne");
//因为原来获取的是Object对象,那么它就只能调用Object的方法,所以想要调用Student的方法只能强转
③方式三:根据id和类型
@Test
public void testDI(){
//获取IOC容器
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
//获取bean
Student student = ioc.getBean("studentThree", Student.class);
System.out.println(student);
}
④注意
当根据类型获取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就可以认定为和类型匹配,能够获取到。
即通过bean的类型,bean所继承的类的类型,bean所实现的接口的类型都可以获取bean
2.2.3、实验三:依赖注入之setter注入
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 + '\'' +
'}';
}
②配置bean时为属性赋值
<bean id="studentOne" class="com.atguigu.spring.bean.Student">
<!-- property标签:通过组件类的setXxx()方法给组件对象设置属性 -->
<!-- name属性:指定属性名(这个属性名是getXxx()、setXxx()方法定义的,和成员变量无关)
-->
<!-- value属性:指定属性值 -->
<property name="id" value="1001"></property>
<property name="name" value="张三"></property>
<property name="age" value="23"></property>
<property name="sex" value="男"></property>
</bean>
③测试
@Test
public void testDI(){
//获取IOC容器
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
//获取bean
Student student = ioc.getBean("studentThree", Student.class);
System.out.println(student);
}
2.2.4、实验四:依赖注入之构造器注入
在student类中添加score属性及其get、set方法
①在Student类中添加有参构造
public Student(Integer sid, String sname, String gender, Integer age) {
this.sid = sid;
this.sname = sname;
this.gender = gender;
this.age = age;
}
public Student(Integer sid, String sname, String gender,Double score) {
this.sid = sid;
this.sname = sname;
this.gender = gender;
this.score = score;
}
②配置bean
<bean id="studentThree" class="com.atguigu.spring.pojo.Student">
<constructor-arg value="1002"></constructor-arg>
<constructor-arg value="李四"></constructor-arg>
<constructor-arg value="女"></constructor-arg>
<constructor-arg value="24" ></constructor-arg>
</bean>
<!--当配置构造器注入,出现有两个满足参数值可以匹配的构造器会选择其中一个并执行,所以可以加构造器参数值属性增加描述,如下-->
注意:
constructor-arg标签还有两个属性可以进一步描述构造器参数:
index属性:指定参数所在位置的索引(从0开始)
name属性:指定参数名
③测试
2.2.5、实验五:特殊值处理
①字面量赋值
什么是字面量?
int a = 10;
声明一个变量a,初始化为10,此时a就不代表字母a了,而是作为一个变量的名字。当我们引用a
的时候,我们实际上拿到的值是10。
而如果a是带引号的:‘a’,那么它现在不是一个变量,它就是代表a这个字母本身,这就是字面
量。所以字面量没有引申含义,就是我们看到的这个数据本身。
②null值
spring-ioc.xml
<bean id="studentFour" class="com.atguigu.spring.pojo.Student">
<property name="sid" value="1001"></property>
<!--
<:<
>:>
CDATA节其中的内容会原样解析<![CDATA[<王五>]]>
CDATA是标签所以必须写在value标签里,不能是value属性
-->
<!--<property name="sname" value="<张三>"></property>-->
<property name="sname" >
<value><![CDATA[<王五>]]></value>
</property>
<property name="age" value="23"></property>
<!--
以下写法,为gender所赋的值是字符串null
<property name="gender" value="null">
</property>
-->
<property name="gender" >
<null></null>
</property>
</bean>
IOCByXmlTest
@Test
public void testDI(){
//获取IOC容器
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
//获取bean
Student student = ioc.getBean("studentFour", Student.class);
System.out.println(student.getGender().toString());//运行结果:null
/*
//property 的value属性赋值为null 如:<property name="gender" value="null"></property>
//gender会被赋值为字面量null,而不是为空,如果为空,student.getGender().toString()会报空指针异常
*/
}
③xml实体
<!-- 小于号在XML文档中用来定义标签的开始,不能随便使用 -->
<!-- 解决方案一:使用XML实体来代替 -->
<property name="expression" value="a < b"/>
④CDATA节
<property name="expression">
<!-- 解决方案二:使用CDATA节 -->
<!-- CDATA中的C代表Character,是文本、字符的含义,CDATA就表示纯文本数据 -->
<!-- XML解析器看到CDATA节就知道这里是纯文本,就不会当作XML标签或属性来解析 -->
<!-- 所以CDATA节中写什么符号都随意 -->
<value><![CDATA[a < b]]></value>
</property>
2.2.6、实验六:为类类型属性赋值
①创建班级类Clazz
public class Clazz {
private Integer clazzId;
private String clazzName;
public Integer getClazzId() {
return clazzId;
}
public void setClazzId(Integer clazzId) {
this.clazzId = clazzId;
}
public String getClazzName() {
return clazzName;
}
public void setClazzName(String clazzName) {
this.clazzName = clazzName;
}
@Override
public String toString() {
return "Clazz{" +
"clazzId=" + clazzId +
", clazzName='" + clazzName + '\'' +
'}';
}
public Clazz() {
}
public Clazz(Integer clazzId, String clazzName) {
this.clazzId = clazzId;
this.clazzName = clazzName;
}
}
②修改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.atguigu.spring.bean.Clazz">
<property name="clazzId" value="1111"></property>
<property name="clazzName" value="财源滚滚班"></property>
</bean>
为Student中的clazz属性赋值:
<bean id="studentFour" class="com.atguigu.spring.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="赵六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
<property name="clazz" ref="clazzOne"></property>
<!--
错误演示 <property name="clazz" value="clazzOne"></property>
-->
</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来赋值
④方式二:内部bean
<bean id="studentFour" class="com.atguigu.spring.bean.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中再声明一个bean就是内部bean -->
<!-- 内部bean只能用于给属性赋值,不能在外部通过IOC容器获取,因此可以省略id属性 -->
<bean id="clazzInner" class="com.atguigu.spring.bean.Clazz">
<property name="clazzId" value="2222"></property>
<property name="clazzName" value="远大前程班"></property>
</bean>
</property>
</bean>
③方式三:级联属性赋值
<bean id="studentFour" class="com.atguigu.spring.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="赵六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<!-- 一定先引用某个bean为属性赋值,才可以使用级联方式更新属性 -->
<!--级联方式没有给clazz实列化会报错:NullValueInNestedPathException:Value of nested property 'clazz' is null-->
<property name="clazz" ref="clazzOne"></property>
<property name="clazz.clazzId" value="3333"></property>
<property name="clazz.clazzName" value="最强王者班"></property>
</bean>
2.2.7、实验七:为数组类型属性赋值
①修改Student类
在Student类中添加以下代码:
private String[] hobbies;
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
②配置bean
<bean id="studentFour" class="com.atguigu.spring.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="赵六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
<property name="clazz" ref="clazzOne"></property>
<property name="hobbies">
<array>
<!--存储类型是字面量类型,那么就用value标签,如果是类类型,就用ref-->
<value>抽烟</value>
<value>喝酒</value>
<value>烫头</value>
</array>
</property>
</bean>
2.2.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="clazzTwo" class="com.atguigu.spring.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>
若为Set集合类型属性赋值,只需要将其中的list标签改为set标签即可
②为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.atguigu.spring.pojo.Teacher">
<property name="tid" value="10086"></property>
<property name="tname" value="大宝"></property>
</bean>
<bean id="teacherTwo" class="com.atguigu.spring.pojo.Teacher">
<property name="tid" value="10010"></property>
<property name="tname" value="小宝"></property>
</bean>
<bean id="studentFive" class="com.atguigu.spring.pojo.Student">
<property name="sid" value="1004"></property>
<property name="sname" value="赵六"></property>
<property name="age" value="26"></property>
<property name="gender" value="男"></property>
<!--引用方式-->
<property name="teacherMap" ref="teacherMap"></property>
<!--
字面量赋值方式
<property name="teacherMap">
<map>
<entry key="10086" value-ref="teacherOne"></entry>
<entry key="10010" value-ref="teacherTwo"></entry>
</map>
</property>
-->
</bean>
③引用集合类型的bean
<!--配置一个集合类型的bean,需要使用util约束,util标签前缀的作用有避免歧义-->
<util:list id="studentList">
<ref bean="studentOne"></ref>
<ref bean="studentTwo"></ref>
<ref bean="studentThree"></ref>
</util:list>
<util:map id="teacherMap">
<entry key="10086" value-ref="teacherOne"></entry>
<entry key="10010" value-ref="teacherTwo"></entry>
</util:map>
使用util:list、util:map标签必须引入相应的命名空间,可以通过idea的提示功能选择
2.2.9、实验九:p命名空间
引入p命名空间后,可以通过以下方式为bean的各个属性赋值
2.2.10、实验十:引入外部属性文件
①加入依赖
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
②创建外部属性文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.username=root
jdbc.password=
③引入属性文件
spring-datasource.xml
<!--引入jdbc.properties,之后就可以通过${key}的方式问value-->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
④配置bean
<!--ioc容器是管理对象的,所以数据源也可以被管理-->
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<!--
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
-->
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
⑤测试
public class DataSourceTest {
@Test
public void testDataSource() throws Exception{
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-datasource.xml");
DruidDataSource dataSource = ioc.getBean(DruidDataSource.class);
System.out.println(dataSource.getConnection());
}
}
2.2.11、实验十一:bean的作用域
①概念
在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围,各取值含义参加下表:
如果是在WebApplicationContext环境下还会有另外两个作用域(但不常用):
②创建类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 +
'}';
}
}
③配置bean
<!--
scope:设置bean的作用域
scope="singleton/prototype"
singleton(单例):表示获取该bean所对应的对象都是同一个
prototype(多例):表示获取该bean所对应的对象都不是同一个
默认配置模式是单例
-->
<!-- scope属性:取值singleton(默认值),bean在IOC容器中只有一个实例,IOC容器初始化时创建 对象 -->
<!-- scope属性:取值prototype,bean在IOC容器中可以有多个实例,getBean()时创建对象 -->
<bean id="student" class="com.atguigu.spring.pojo.Student" scope="prototype">
<property name="sid" value="1001"></property>
<property name="sname" value="张三"></property>
</bean>
④测试
public class ScopeTest {
@Test
public void testScope(){
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-scope.xml");
Student student1 = ioc.getBean(Student.class);
Student student2 = ioc.getBean(Student.class);
System.out.println(student1 == student2);//没有重写equal的比较的是地址
//String类型的变量会先去常量池寻找有无此变量,没有则创建一个,所以相同String的== 比较地址无用,都是同一个地址
// 所以String要重写equal,比较内容
}
}
2.2.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("生命周期:4、销毁");
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
注意其中的initMethod()和destroyMethod(),可以通过配置bean指定为初始化和销毁的方法
③配置bean
<!-- 使用init-method属性指定初始化方法 -->
<!-- 使用destroy-method属性指定销毁方法 -->
<bean id="user" class="com.atguigu.spring.pojo.User" init-method="initMethod" destroy-method="destroyMethod" >
<property name="id" value="1"></property>
<property name="username" value="admin"></property>
<property name="password" value="123456"></property>
<property name="age" value="23"></property>
</bean>
④测试
public class LifeCycleTest {
/**
* 1.实例化
* 2.依赖注入
* 3.后置处理器的postProcessBeforeInitialization
* 4.初始化,需要通过bean的init-method属性指定初始化的方法
* 5.后置处理器的postProcessAfterInitialization
* 6.IOC容器关闭时销毁,需要通过bean的destory-method属性指定初始化的方法
*
* 注意:
* 若bean的作用域为单例时,生命周期的前三个步骤会在获取IOC容器时执行
* 若bean的作用域为多例时,生命周期的前三个步骤会在获取bean时执行
*/
@Test
public void test(){
//ConfigurableApplicationContext是ApplicationContex的子接口,其中扩展了刷新和关闭容器的方法
ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
//单例模式时在创建ioc时就执行了生命周期前三个步骤:1、创建对象/实列化 2、依赖注入 3、初始化,以后都用同一个此对象
//当设置为多例模式时在获取bean对象时才创建,每一次获取都是不同对象被创建
User user = ioc.getBean(User.class);
System.out.println(user);
ioc.close();
}
}
⑤bean的后置处理器
bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口,
且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容
器中所有bean都会执行
创建bean的后置处理器:
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//此方法在bean的生命周期初始化之前实行
System.out.println("MyBeanPostProcessor-->后置处理器postProcessBeforeInitialization");
return null;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//此方法在bean的生命周期初始化之后实行
System.out.println("MyBeanPostProcessor-->后置处理器postProcessAfterInitialization");
return null;
}
}
在IOC容器中配置后置处理器:
<!-- bean的后置处理器要放入IOC容器才能生效 -->
<bean id="myBeanProcessor" class="com.atguigu.spring.process.MyBeanProcessor"/>
2.2.13、实验十三:FactoryBean
①简介
FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个
FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是
getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都
屏蔽起来,只把最简洁的使用界面展示给我们。
将来我们整合Mybatis时,Spring就是通过FactoryBean机制来帮我们创建SqlSessionFactory对象的。
②创建类UserFactoryBean
/**
* FactoryBean是一个接口,需要创建一个类实现该接口
* 其中有三个方法:
* getObject();通过一个对象交给IOC容器
* getObjectType():设置所提供对象的类型
* isSingleton():所提供的对象是否单例
* 当把FactoryBean的实现类配置为bean时,会将当前类中getObject()所返回的对象交给IOC容器管理
*/
public class UserFactoryBean implements FactoryBean<User>{
public User getObject() throws Exception {
return new User();
}
public Class<?> getObjectType() {
return User.class;
}
}
③配置bean
<!--配置的是UserFactoryBean类型,不过返回的是UserFactoryBean里getObject的返回值-->
<bean class="com.atguigu.spring.factory.UserFactoryBean"></bean>
④测试
public class FactoryBeanTest {
@Test
public void testFctory(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-factory.xml");
User user = ioc.getBean(User.class);
System.out.println(user);
}
}
2.2.14、实验十四:基于xml的自动装配
自动装配:
根据指定的策略,在IOC容器中匹配某一个bean,自动为指定的bean中所依赖的类类型或接口类型属性赋值
①场景模拟
创建类UserController
public class UserController {
/*private UserService userService = new UserServiceImpl();
* 这种是硬编码,写死了,需要更新维护时,一般不会在原有代码上改,会选择扩展新的实现类
* 硬编码就需要更改,重新编译,生成jar包才有效
*/
/*
ioc是管理对象及其依赖关系的,这时就可以把UserController交给ioc管理
ioc给予什么对象就是什么对象,而且要更换新的实现类,只需要更改为新的实现类的bean id
*/
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{
public void saveUser() {
System.out.println("保存成功");
}
}
②配置bean
使用bean标签的autowire属性设置自动装配效果
自动装配方式:byType
byType:根据类型匹配IOC容器中的某个兼容类型的bean,为属性自动赋值
若在IOC中,没有任何一个兼容类型的bean能够为属性赋值,则该属性不装 配,即值为默认值 null
若在IOC中,有多个兼容类型的bean能够为属性赋值,则抛出异常
NoUniqueBeanDefinitionException
<bean id="userController" class="com.atguigu.spring.controller.UserController" autowire="byType">
<!--<property name="userService" ref="userService"></property>-->
</bean>
<bean id="userService" class="com.atguigu.spring.service.impl.UserServiceImpl" autowire="byType">
<!--<property name="userDao" ref="userDao"></property>-->
</bean>
<bean id="userDao" class="com.atguigu.spring.dao.impl.UserDaoImpl"></bean>
自动装配方式:byName
byName:将自动装配的属性的属性名,作为bean的id在IOC容器中匹配相对应的bean进行赋值
③测试
public class AutowireByXML {
/**
* 自动装配:
* 根据指定的策略,在IOC容器中匹配某个bean,自动为bean中的类类型的属性或接口类型的属性赋值
*可以通过bean标签中的autowire属性设置自动装配的策略
* 自动装配的策略:
* 1.no,default:表示不装配,即bean中的属性不会自动匹配某个bean为属性赋值,此时属性使用默认值
* 2.byType:根据要赋值的属性的类型,在IOC容器中匹配某个bean,为属性赋值
*
* 注意:
* a>若通过类型没有找到任何一个类型匹配的bean,此时不装配,属性使用默认值
* b>若通过类型找到了多个类型匹配的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
2.3.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、@Service、@Repository这三个注解只是在@Component注解
的基础上起了三个新的名字。
对于Spring使用IOC容器管理这些组件来说没有区别。所以@Controller、@Service、@Repository这三个注解只是给开发人员看的,让我们能够便于分辨组件的作用。
注意:虽然它们本质上一样,但是为了代码的可读性,为了程序结构严谨我们肯定不能随便胡乱标记。
⑥创建组件
创建控制层组件
@Controller("controller")
public class UserController {
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void saveUser(){
userService.saveUser();
}
}
创建接口UserService
public interface UserService {
void saveUser();
}
``
创建业务层组件UserServiceImpl`
```java
public class UserServiceImpl implements UserService{
private UserDao userDao;
public void saveUser() {
userDao.saveUser();
}
//当实现类没有实现接口,报错如下
//NoSuchBeanDefinitionException: No qualifying bean of type 'com.atguigu.spring.service.UserService' available
}
创建接口UserDao
public interface UserDao {
/**
* 保存用户信息
*/
void saveUser();
}
创建持久层组件UserDaoImp
@Repository
public class UserDaoImpl implements UserDao{
public void saveUser() {
System.out.println("保存成功");
}
}
⑦扫描组件
情况一:最基本的扫描方式
<context:component-scan base-package="com.atguigu">
</context:component-scan>
情况二:指定要排除的组件
<!--扫描组件-->
<contxt:component-scan base-package="com.atguigu.spring" >
<!--
context:exclude-filter:排除扫描
type:设置排除扫描的方式
type="annotation/assignable"
annotation:根据注解的类型进行排除,expression需要设置排除的注解的全类名
assignable:根据类的类型进行排除,expressionu需要设置排除的类的全类名
以后在SSM整合中,SpringMVC需要扫描控制层,Spring需要扫描除控制层以外的其他组件
所以排除标签多用根据注解排除
-->
<contxt:exclude-filter type="assignable" expression="com.atguigu.spring.controller.UserController"/>
</contxt:component-scan>
情况三:仅扫描指定组件
<!--扫描组件-->
<contxt:component-scan base-package="com.atguigu.spring" >
<!--
contxt:include-filter:包含扫描
注意:
use-default-filters 默认为true ,所设置的包下所有的类都需要扫描,若使用排除扫描
需要在context:component-scan标签中设置use-default-filters="false"
-->
<contxt:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</contxt:component-scan>
⑧测试
@Test
public void testAutowireByAnnotation(){
ApplicationContext ac = new
ClassPathXmlApplicationContext("applicationContext.xml");
UserController userController = ac.getBean(UserController.class);
System.out.println(userController);
UserService userService = ac.getBean(UserService.class);
System.out.println(userService);
UserDao userDao = ac.getBean(UserDao.class);
System.out.println(userDao);
}
⑨组件所对应的bean的id
在我们使用XML方式管理bean的时候,每个bean都有一个唯一标识,便于在其他地方引用。现在使用注解后,每个组件仍然应该有一个唯一标识。
默认情况类名首字母小写就是bean的id。 例如:UserController类对应的bean的id就是userController。
自定义bean的id可通过标识组件的注解的value属性设置自定义的bean的id
@Service(“userService”)//默认为userServiceImpl public class UserServiceImpl implements
UserService {}
2.3.2、实验二:基于注解的自动装配
①场景模拟
参考基于xml的自动装配
在UserController中声明UserService对象
在UserServiceImpl中声明UserDao对象
②@Autowired注解
在成员变量上直接标记@Autowired注解即可完成自动装配,不需要提供setXxx()方法。以后我们在项目中的正式用法就是这样。
@Controller("controller")
public class UserController {
@Autowired(required = false)//基于xml里是用的autowire属性,且需要有成员变量的set、get方法;这里使用注解实现自动装配不需要set方法
@Qualifier("service")
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void saveUser(){
userService.saveUser();//没有设置自动注解,这里会报空指针
}
}
public interface UserService {
void saveUser();
}
``
```java
public class UserServiceImpl implements UserService{
@Autowired()
@Qualifier("userDaoImpl")
private UserDao userDao;
public void saveUser() {
userDao.saveUser();
}
//当实现类没有实现接口,报错如下
//NoSuchBeanDefinitionException: No qualifying bean of type 'com.atguigu.spring.service.UserService' available
}
public interface UserDao {
/**
* 保存用户信息
*/
void saveUser();
}
@Repository
public class UserDaoImpl implements UserDao{
public void saveUser() {
System.out.println("保存成功");
}
}
③@Autowired注解其他细节
@Autowired注解可以标记在构造器和set方法上
- b>标识在set方法上
- c>标识在为当前成员变量赋值的有参构造上
*** ④@Autowired工作流程**
首先根据所需要的组件类型到IOC容器中查找
能够找到唯一的bean:直接执行装配
如果完全找不到匹配这个类型的bean:装配失败
和所需类型匹配的bean不止一个
没有@Qualifier注解:根据@Autowired标记位置成员变量的变量名作为bean的id进行匹配
能够找到:执行装配
找不到:装配失败
使用@Qualifier注解:根据@Qualifier注解中指定的名称作为bean的id进行匹配
能够找到:执行装配
找不到:装配失败
spring-ioc-annotation.xml
<!--扫描组件-->
<contxt:component-scan base-package="com.atguigu.spring" >
</contxt:component-scan>
<bean id="service" class="com.atguigu.spring.service.impl.UserServiceImpl"></bean>
<bean id="dao" class="com.atguigu.spring.dao.impl.UserDaoImpl"></bean>
测试
public class IOCAnnotationTest {
/**
*@Component:将类标识为普通组件
* @Controller:将类标识为控制层组件
* @Service:将类标识为业务层组件
*@Repository:将类标识为持久层组件
*
* 通过注解+扫描所配置的bean的id,默认为类的小驼峰,即类名的首字母为小写的结果
* 可以通过标识组件的注解的value属性值设置bean的自定义的id
*
* @Autowired:实现自动装配功能的注解
* 1、@Autowired注解能够标识的位置
* a>标识在成员变量身上,此时不需要设置成员变量的set方法
* b>标识在set方法上
* c>标识在为当前成员变量赋值的有参构造上
* 2.@Autowired的原理
* a>默认通过byType的方式,在IOC容器中通过类型匹配某个bean为属性赋值
* b>若有多个类型匹配的bean,此时会自动转换为byName的方式实现自动装配的效果
* 即将要赋值的属性的属性名作为bean的id匹配某个bean为属性赋值
* c>若byType和byName的方式都无防实现自动装配,即IOC容器中有多个类型的bean
* 且这些bean的id和要赋值的属性的属性名都不一致,此时抛异常:NoUniqueBeanDefinitionException
* d>此时可以在要赋值的属性上,添加一个注解@Qualifier
* 通过该注解的value属性值,指定某个bean的id,将这个bean为属性赋值
*
* 注意:若IOC容器中没有任何一个类型匹配的bean,此时抛出异常NoUniqueBeanDefinitionException
* 在@Autowired注解中有个属性required,默认值为true,要求必须完成自动装配
* 可以将required设置为false,
*/
@Test
public void test(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc-annotation.xml");
UserController userController = ioc.getBean("controller",UserController.class);
System.out.println(userController);
userController.saveUser();
}
}
@Autowired中有属性required,默认值为true,因此在自动装配无法找到相应的bean时,会装配失败
可以将属性required的值设置为true,则表示能装就装,装不上就不装,此时自动装配的属性为默认值
但是实际开发时,基本上所有需要装配组件的地方都是必须装配的,用不上这个属性。