Bean 作用域和生命周期

Bean 作用域和生命周期

1.通过⼀个案例来看 Bean 作用域的问题

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

1.1 被修改的 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("s
pring-config.xml");
 BeanScopesController beanScopesController = context.getBean(BeanSc
opesController.class);
 System.out.println("A 对象修改之后 Name:" + beanScopesController.ge
tUser1().toString());
 BeanScopesController2 beanScopesController2 = context.getBean(Bean
ScopesController2.class);
 System.out.println("B 对象读取到的 Name:" + beanScopesController2.g
etUser1().toString());
 }
}

执行结果如下
在这里插入图片描述

1.2原因分析

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

2.作用域定义

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

2.1 Bean 的 6 种作用域

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

2.1.1. 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.1.2. prototype:原型作用域(多例作用域)

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

2.1.3. 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 SpringApplicationContext.
描述:每次http请求会创建新的Bean实例,类似于prototype
场景:一次http的请求和响应的共享Bean
备注:限定SpringMVC中使用

2.1.4. 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.1.5. 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.1.6. websocket:HTTP 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.2设置作用域

使用 @Scope 标签就可以用声明 Bean 的作用域,比如设置 Bean 的作用域

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

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

  1. 直接设置值:@Scope(“prototype”)
  2. 使用枚举设置:@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

3.Spring 执行流程和 Bean 的生命周期

3.1 Spring 执行流程

在这里插入图片描述
Spring 执行流程:
1.启动容器
2.读取配置进行Bean初始化
3.将Bean加入到容器中
4.装配Bean属性(给当前类的属性DI,进行赋值)
5.spring项目运行
6.执行spring相关业务代码
7.释放Bean,销毁Bean
8.关闭容器

3.2 Bean 生命周期

所谓的生命周期指的是⼀个对象从诞生到销毁的整个生命过程,我们把这个过程就叫做⼀个对象的生命
周期。
Bean 的生命周期分为以下 几 大部分:
1.启动容器
2.实例化 Bean(为 Bean 分配内存空间)(买房子,这块个房子就属于你了,但是还没建造)
3.设置属性(Bean 注入和装配)(钢筋水泥的建房子)
4.Bean 初始化(给房装修)
实现了各种 Aware 通知的方法,如 BeanNameAware、BeanFactoryAware、ApplicationContextAware 的接⼝方法;
执行 BeanPostProcessor 初始化前置方法;
执行 @PostConstruct 初始化方法,依赖注⼊操作之后被执⾏;
执行自己指定的 init-method 方法(如果有指定的话);
执行 BeanPostProcessor 初始化后置方法
简单来说就是:
实现了各种 通知的方法
初始化前置方法
初始化方法
初始化后置方法
5.使用Bean(住进去)
6.销毁 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 htt
p://www.springframework.org/schema/beans/spring-beans.xsd http://www.sprin
gframework.org/schema/context https://www.springframework.org/schema/conte
xt/spring-context.xsd">
 <content:component-scan base-package="com.bit.component"></content:com
ponent-scan>
 <beans>
 <bean id="beanLifeComponent" class="com.bit.component.BeanLifeComp
onent" 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();
 }
}

为什么要先设置属性在进行初始化呢?
因为在初始化的时候可能会调用属性对应的方法,比如下图第二个红色圈圈,这时候如果user没被赋值(设置属性),就会空指针异常,因此要先设置属性再进行初始化
在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值