JAVA Bean 对象的作用域和生命周期

1. 作用域

1.1 作用域定义

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

1.2 Bean 的 6 种作⽤域

1.2.1 singleton(单例作⽤域)

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

1.2.2 prototype (原型作⽤域 / 多例作⽤域)

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

1.2.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 beandefinition. Only valid in the context of a web-aware Spring ApplicationContext.
  • 描述:每次http请求会创建新的Bean实例,类似于prototype
  • 场景:⼀次http的请求和响应的共享Bean
  • 备注:限定SpringMVC中使⽤

1.2.4 session:(会话作⽤域)

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

1.2.5 application:(全局作⽤域)

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

1.2.6 websocket:(HTTP WebSocket 作⽤域)

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

Spring 中只能使用前两种

singleton 和 application 的区别:

  1. singleton 作⽤于 IoC 的容器,⽽ application 作⽤于 Servlet 容器
  2. singleton 是 Spring Core 的作⽤域;application 是 Spring Web 中的作⽤域

1.3 设置作用域

使⽤ @Scope 标签就可以⽤来声明 Bean 的作⽤域
@Scope 的参数可以有两种方式:

  1. 直接在括号中声明作用域类型, 例如: @Scope(“prototype”)
  2. 使用全家变量作为参数, 例如: @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

2. 生命周期

所谓的⽣命周期指的是⼀个对象从诞⽣到销毁的整个⽣命过程,我们把这个过程就叫做⼀个对象的⽣命周期。
Bean 的⽣命周期分为以下 5 ⼤部分:
1.实例化 Bean(为 Bean 分配内存空间)
2.设置属性(Bean 注⼊和装配)
3.Bean 初始化

  • 实现了各种 Aware 通知的⽅法,如 BeanNameAware、 BeanFactoryAware、ApplicationContextAware 的接⼝⽅法;
  • 执⾏ BeanPostProcessor 初始化前置⽅法;
  • 执⾏ @PostConstruct 初始化⽅法,依赖注⼊操作之后被执⾏;
  • 执⾏⾃⼰指定的 init-method ⽅法(如果有指定的话);
  • 执⾏ BeanPostProcessor 初始化后置⽅法。

4.使⽤ Bean
5.销毁 Bean

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

猜你喜欢

转载自blog.csdn.net/m0_71645055/article/details/132301095