Bean的作用域和生命周期

从前面的博客我们可以看出 Spring 是用来读取和存储 Bean ,因此在 Spring Bean 是最核心的操作资源,所以接下来我们深入学习一下 Bean 对象。

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

假设现在有一个公共的 Bean ,提供给 A 用户和 B 用户使用,然而在使用的途中 A 用户却 悄悄 地修改了公共 Bean 的数据,导致 B 用户在使用时发生了预期之外的逻辑错误。
我们预期的结果是,公共 Bean 可以在各自的类中被修改,但不能影响到其他类。

被修改的 Bean 案例

公共 Bean
@Component
public class Users {
@Bean
public User user1() {
User user = new User();
user.setId(1);
user.setName("Java"); // 【重点:名称是 Java】
return user;
    }
}
A 用户使用时,进行了修改操作:
@Controller
public class BeanScopesController {
@Autowired
private 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 {
@Autowired
private 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("springconfig.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 默认情况下是单例状态( singleton ),也就是所有人的使用的都是同一个对象,之前我们学单例模式的时候都知道,使用单例可以很大程度上提高性能,所以在 Spring 中 Bean 的作用域默认也是 singleton 单例模式。

作用域定义

限定程序中变量的可用范围叫做作用域,或者说在源代码中定义变量的某个区域就叫做作用域。
Bean 的作用域是指 Bean Spring 整个框架中的某种行为模式,比如 singleton 单例作用域,就 表示 Bean 在整个 Spring 中只有一份,它是全局共享的,那么当其他人修改了这个值之后,那么另一 个人读取到的就是被修改的值

Bean 6 种作用域

Spring 容器在初始化一个 Bean 的实例时,同时会指定该实例的作用域。 Spring 6 种作用域,最后四种是基于 Spring MVC 生效的:
1. singleton :单例作用域
2. prototype :原型作用域(多例作用域)
3. request :请求作用域
4. session :回话作用域
5. application :全局作用域
6. websocket HTTP WebSocket 作用域
注意后 4 种状态是 Spring MVC 中的值,在普通的 Spring 项目中只有前两种。

singleton

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

prototype

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

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中使用

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中使用

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中使用

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中使用

单例作用域(singleton)和全局作用域(application)区别

singleton Spring Core 的作用域; application Spring Web 中的作用域;
singleton 作用于 IoC 的容器,而 application 作用于 Servlet 容器。

Bean 原理分析

接下来,咱们来看一下 Bean 执行原理和生命周期总结。

Bean 执行流程

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

Bean 生命周期

所谓的生命周期指的是一个对象从诞生到销毁的整个生命过程,我们把这个过程就叫做一个对象的生命周期。
Bean 的生命周期分为以下 5 大部分:

1.实例化 Bean

Bean 分配内存空间

2.设置属性

Bean 注入和装配

3.Bean 初始化

  • 实现了各种 Aware 通知的方法,如 BeanNameAwareBeanFactoryAware
  • ApplicationContextAware 的接口方法;
  • 执行 BeanPostProcessor 初始化前置方法;
  • 执行 @PostConstruct 初始化方法,依赖注入操作之后被执行;
  • 执行自己指定的 init-method 方法(如果有指定的话);
  • 执行 BeanPostProcessor 初始化后置方法。

4.使用 Bean

5.销毁 Bean

销毁容器的各种方法,如 @PreDestroy DisposableBean 接口方法、 destroy-method
执行流程如下图所示:

实例化和初始化的区别

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

生命流程的故事

Bean 的生命流程看似繁琐,但咱们可以以生活中的场景来理解它,比如我们现在需要买一栋房子,那么我们的流程是这样的:
1. 先买房(实例化,从无到有);
2. 装修(设置属性);
3. 买家电,如洗衣机、冰箱、电视、空调等([各种 ] 初始化);
4. 入住(使用 Bean );
5. 卖出去( Bean 销毁)。

生命周期演示

import org.springframework.beans.factory.BeanNameAware;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Component
public class BeanLifeComponent implements BeanNameAware {
@PostConstruct
public void postConstruct() {
System.out.println("执行 PostConstruct()");
}
public void init() {
System.out.println("执行 BeanLifeComponent init-method");
}
@PreDestroy
public void preDestroy() {
System.out.println("执行:preDestroy()");
}
public void setBeanName(String s) {
System.out.println("执行了 setBeanName 方法:" + s);
    }
}

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.bit.component">
</content:component-scan>
<beans>
<bean id="beanLifeComponent" class="com.bit.component.BeanLifeComponent"
init-method="init"></bean>
</beans>
</beans>
调用类:
import com.bit.controller.BeanLife;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class BeanLifeTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("spring-config.xml");
BeanLife life = context.getBean(BeanLife.class);
System.out.println("执行 main 方法");
// 执行销毁方法
context.destroy();
    }
}

总结

本篇博客介绍了 Bean 6 种作用域:
1. singleton :单例作用域
2. prototype :原型作用域(多例作用域)
3. request :请求作用域
4. session :回话作用域
5. application :全局作用域
6. websocket HTTP WebSocket 作用域
其中前两种是 spring 核心作用域,而后 4 种是 spring mvc 中的作用域,也介绍了 spring 的执行流程和bean 的生命周期,其中 bean 的作用域是最重要的知识点也是常见的面试题,而 bean 大的执行流程也一定要知道。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值