当前位置: 首页 > news >正文

Spring | Bean 作用域和生命周期

一、通过一个案例来看 Bean 作用域的问题

Spring 是用来读取和存储 Bean,因此在 Spring 中 Bean 是最核心的操作资源,所以接下来我们深入学习⼀下 Bean 对象

假设现在有⼀个公共的 Bean,提供给 A 用户和 B 用户使用,然而在使用的途中 A 用户却 “悄悄” 地修改了公共 Bean 的数据,导致 B 用户在使用时发生了预期之外的逻辑错误

我们预期的结果是,公共 Bean 可以在各自的类中被修改,但不能影响到其他类

1、被修改的 Bean 案例

——公共 Bean:

@Component
public class Users {@Beanpublic User user1() {User user = new User();user.setId(1);user.setName("Java"); // 【重点:名称是 Java】return user;}
}

——A 用户使用时,进行了修改操作:

@Controller
public class BeanScopesController {@Autowiredprivate User user1;public User getUser1() {User user = user1;System.out.println("Bean 原 Name:" + user.getName());user.setName("悟空"); // 【重点:进行了修改操作】return user;}
}

——B 用户再去使用公共 Bean 的时候:

@Controller
public class BeanScopesController2 {@Autowiredprivate User user1;public User getUser1() {User user = user1;return user;}
}

——打印 A 用户和 B 用户公共 Bean 的值:

public class BeanScopesTest {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");BeanScopesController beanScopesController = context.getBean(BeanScopesController.class);System.out.println("A 对象修改之后 Name:" + beanScopesController.getUser1().toString());BeanScopesController2 beanScopesController2 = context.getBean(BeanScopesController2.class);System.out.println("B 对象读取到的 Name:" + beanScopesController2.getUser1().toString());}
}

——执行结果如下:

Bean 原 Name: Java (原来的值)
A 对象修改之后 Name: 1:悟空 (被 A 对象修改)
B 对象读取到的 Name: 1:悟空 (B 对象中也跟着被更新了)


2、原因分析

操作以上问题的原因是因为 Bean 默认情况下是单例状态(singleton),也就是所有⼈的使用的都是同⼀个对象,之前我们学单例模式的时候都知道,使用单例可以很⼤程度上提高性能,所以在 Spring 中Bean 的作用域默认也是 singleton 单例模式


二、作用域定义 Scope

限定程序中变量的可用范围叫做作用域,或者说在源代码中定义变量的某个区域就叫做作用域

而 Bean 的作用域是指 Bean 在 Spring 整个框架中的某种行为模式,⽐如 singleton 单例作用域,就表示 Bean 在整个 Spring 中只有⼀份,它是全局共享的,那么当其他⼈修改了这个值之后,那么另⼀个⼈读取到的就是被修改的值


1、Bean 的 6 种作用域

Spring 容器在初始化⼀个 Bean 的实例时,同时会指定该实例的作用域。Spring有 6 种作用域,最后四种是基于 Spring MVC 生效的:

  1. singleton :单例作用域(默认)

  2. prototype :原型作用域(多例作用域)

  3. request :请求作用域(Spring MVC)

  4. session :回话作用域(Spring MVC)

  5. application :全局作用域(Spring MVC)

  6. websocket :HTTP WebSocket 作用域(Spring WebSocket)

注意后 4 种状态是 Spring MVC 中的值,在普通的 Spring 项目中只有前两种


2、设置 bean 作用域

@scope 标签既可以修饰方法,也可以修饰类,有两种设置方式:

  • 直接设置值:@Scope("prototype")
  • 类似枚举常量的设置:@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

2.1、测试 Bean 默认是那种作用域

——UserBeans:

@Component
public class UserBeans {@Bean(name = "user1")public User getUser1() {User user = new User();user.setId(1);user.setName("zhangsan");return user;}@Bean(name = "user2")public User getUser2() {User user = new User();user.setId(2);user.setName("lisi");return user;}@Bean(name = "user3")public User getUser3() {User user = new User();user.setId(3);user.setName("Java");return user;}
}

——创建类 BeanScope1:

@Component
public class BeanScope1 {@Autowired // 注入 user3private User user3;public User getUser3() {User user = user3;user.setName("八戒");return user;}
}

——创建类 BeanScope2:

@Component
public class BeanScope2 {@Autowiredprivate User user3;public User getUser3() {return user3;}
}

——测试:

public class App {public static void main(String[] args) {ApplicationContext context = newClassPathXmlApplicationContext("spring-config.xml");BeanScope1 beanScope1 = context.getBean(BeanScope1.class);User user1 = beanScope1.getUser3();System.out.println("BeanScope1" + user1);BeanScope2 beanScope2 = context.getBean(BeanScope2.class);User user2 = beanScope2.getUser3();System.out.println("BeanScope2" + user2);}
}

运行结果: 说明默认为单例

BeanScope1User{id=3, name=‘八戒’}
BeanScope2User{id=3, name=‘八戒’}


2.2、设置作用域

  • @Scope(“prototype”)
@Bean(name = "user3")
@Scope("prototype") // 原型模式,每次请求生成一个对象
public User getUser3() {User user = new User();user.setId(3);user.setName("Java");return user;
}

运行结果:

BeanScope1User{id=3, name=‘八戒’}
BeanScope2User{id=3, name=‘Java’}

  • @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    @Bean(name = "user3")@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)public User getUser3() {User user = new User();user.setId(3);user.setName("Java");return user;}

在这里插入图片描述

运行结果:

BeanScope1User{id=3, name=‘八戒’}
BeanScope2User{id=3, name=‘Java’}


2.3、singleton

官方说明:(Default) Scopes a single bean definition to a single object instance for each
Spring IoC container.
描述:该作⽤域下的Bean在IoC容器中只存在⼀个实例:获取Bean(即通过
applicationContext.getBean等方法获取)及装配Bean(即通过@Autowired注⼊)都是同⼀
个对象。
场景:通常无状态的Bean使⽤该作⽤域。无状态表示Bean对象的属性状态不需要更新
备注:Spring默认选择该作⽤域


2.4、prototype

官方说明:Scopes a single bean definition to any number of object instances.
描述:每次对该作⽤域下的Bean的请求都会创建新的实例:获取Bean(即通过
applicationContext.getBean等方法获取)及装配Bean(即通过@Autowired注⼊)都是新的
对象实例。
场景:通常有状态的Bean使⽤该作⽤域


2.5、request

官方说明:Scopes a single bean definition to the lifecycle of a single HTTP request. That
is, each HTTP request has its own instance of a bean created off the back of a single
bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
描述:每次http请求会创建新的Bean实例,类似于prototype
场景:⼀次http的请求和响应的共享Bean
备注:限定SpringMVC中使⽤


2.6、session

官方说明:Scopes a single bean definition to the lifecycle of an HTTP Session. Only
valid in the context of a web-aware Spring ApplicationContext.
描述:在⼀个http session中,定义⼀个Bean实例
场景:⽤户回话的共享Bean, ⽐如:记录⼀个⽤户的登陆信息
备注:限定SpringMVC中使⽤


2.7、application(了解)

官方说明:Scopes a single bean definition to the lifecycle of a ServletContext. Only valid
in the context of a web-aware Spring ApplicationContext.
描述:在⼀个http servlet Context中,定义⼀个Bean实例
场景:Web应⽤的上下⽂信息,⽐如:记录⼀个应⽤的共享信息
备注:限定SpringMVC中使⽤


2.8、websocket(了解)

官方说明:Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in
the context of a web-aware Spring ApplicationContext.
描述:在⼀个HTTP WebSocket的生命周期中,定义⼀个Bean实例
场景:WebSocket的每次会话中,保存了⼀个Map结构的头信息,将⽤来包裹客户端消息
头。第⼀次初始化后,直到WebSocket结束都是同⼀个Bean。
备注:限定Spring WebSocket中使⽤


2.9、单例作⽤域(singleton) 和 全局作⽤域(application) 的区别

项目类型不同: singleton 是 Spring Core 的作⽤域;application 是 Spring Web 中的作⽤域;
作用容器不同: singleton 作⽤于 IoC 的容器,而 application 作⽤于 Servlet 容器


3、Bean 原理分析

Bean 执行流程(Spring 执行流程):启动 Spring 容器 -> 实例化 Bean(分配内存空间,从无到有)
-> Bean 注册到 Spring 中(存操作) -> 将 Bean 装配到需要的类中(取操作)

在这里插入图片描述


三、Bean 生命周期

1、5 个流程

所谓的生命周期指的是⼀个对象从诞生到销毁的整个生命过程,我们把这个过程就叫做⼀个对象的生命周期。

Bean 的生命周期分为以下 5 大部分:

  1. 实例化 Bean(为 Bean 分配内存空间)

  2. 设置属性(Bean 注⼊和装配)

  3. Bean 初始化

    • 实现了各种 Aware 通知的方法,如 BeanNameAware、BeanFactoryAware、ApplicationContextAware 的接口方法;

    • 执行 BeanPostProcessor 初始化前置方法;

    • 执行构造方法,有两种执行方式:

    • 注解: @PostConstruct 初始化方法,依赖注⼊操作之后被执行;

    • xml:执行自己指定的 init-method 方法(如果有指定的话);<bean init-method=""></bean>

    • 如果两个都设置了,先执行注解,

    • 执行 BeanPostProcessor 初始化后置方法

  4. 使⽤ Bean

  5. 销毁 Bean

    • 销毁容器的各种方法,如 @PreDestroy (注解)、DisposableBean 接口方法、destroy-method (xml)

2、实例化和初始化的区别

实例化和属性设置是 Java 级别的系统“事件”,其操作过程不可⼈⼯⼲预和修改;而初始化是给
开发者提供的,可以在实例化之后,类加载完成之前进行⾃定义“事件”处理


3、生命流程的“故事”

Bean 的生命流程看似繁琐,但咱们可以以生活中的场景来理解它,比如我们现在需要买一栋房子,那么我们的流程是这样的:

  1. 先买房(实例化,从无到有);

  2. 装修(设置属性);

  3. 买家电,如洗衣机、冰箱、电视、空调等([各种]初始化);

  4. 入住(使用 Bean);

  5. 卖出去(Bean 销毁)


4、生命周期演示

——创建类 BeanLifeComponent:

// @Component // 在 xml 中 使用 bean 标签注入了,不需要类注解
public class BeanLifeComponent implements BeanNameAware {@PostConstructpublic void postConstruct() {System.out.println("执⾏ @PostConstruct()");}public void init() {System.out.println("执⾏ init-method");}public void use() {System.out.println("使用 bean");}@PreDestroypublic void preDestroy() {System.out.println("执⾏ @PreDestroy");}public void setBeanName(String s) {System.out.println("执⾏了 Aware 通知");}
}

——xml 配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:content="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 https://www.springframework.org/schema/context/spring-context.xsd"><content:component-scan base-package="com.beans"></content:component-scan><bean id="beanLifeComponent" class="com.beans.BeanLifeComponent" init-method="init"></bean></beans>

——调⽤类:

public class App {public static void main(String[] args) {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");BeanLifeComponent beanLifeComponent = context.getBean("beanLifeComponent", BeanLifeComponent.class);beanLifeComponent.use();context.destroy(); // 注销上下文对象}
}

运行结果:

执行了 Aware 通知
执行 @PostConstruct()
执行 init-method
使用 bean
执行 @PreDestroy


2、为什么先设置属性再初始化

也就是 步骤 2 和 步骤 3 的顺序,能不能打个颠倒?

@Service
public class UserService {public UserService(){System.out.println("调⽤ User Service 构造⽅法");}public void sayHi(){System.out.println("User Service SayHi.");}
}@Controller
public class UserController {@Resourceprivate UserService userService;@PostConstructpublic void postConstruct() {userService.sayHi(); // 执行构造方法时使用 会空指针System.out.println("执⾏ User Controller 构造⽅法");}
}

http://www.lryc.cn/news/103283.html

相关文章:

  • 培训(c++题解)
  • ansible-playbook编写 lnmp 剧本
  • 需求太多处理不过来?MoSCoW模型帮你
  • Vue 3:玩一下web前端技术(六)
  • 【点云处理教程】00计算机视觉的Open3D简介
  • Windows10系统还原操作
  • Django学习笔记-模板(Template)基础
  • 使用 NVM(Node Version Manager)管理 Node.js 版本
  • (文章复现)梯级水光互补系统最大化可消纳电量期望短期优化调度模型matlab代码
  • tinkerCAD案例:24. Ruler - Measuring Lengths 标尺 -量勺
  • linux系统编程重点复习--线程同步
  • 【Docker 学习笔记】Windows Docker Desktop 安装
  • getInputStream has already been called for this request 问题记录
  • 日撸代码300行:第60天(小结)
  • python和java哪个更有前景,python和java哪个更有前途
  • LeetCode_11. 盛最多水的容器
  • 【Android】APP电量优化学习笔记
  • 【微信小程序创作之路】- 小程序事件绑定、动态提示Toast、对话框 Modal
  • MVC与MVVM模式的区别
  • 【数据结构与算法】归并排序
  • OSG3.6.5 + VS2017前期准备及编译
  • IPv6 over IPv4隧道配置举例
  • 【GitOps系列】使用 ArgoCD 快速打造GitOps工作流
  • C#|无法打开cs文件设计窗口
  • 【SpringBoot笔记36】SpringBoot自定义WebSocketHandler集成WebSocket
  • flutter 图片相关
  • 将上位机程序从PC的window系统迁移至Intel NUC的无桌面版ubuntu系统问题记录
  • CHI中的error处理
  • 如何使用 PHP 进行数据库缓存处理?
  • 新版巨量广告投放技巧分析