0
点赞
收藏
分享

微信扫一扫

【Spring】- 生命周期回调

【Bean初始化】

官方使用建议建议您不要使用InitializingBean接口,因为它不必要地将代码耦合到 Spring。另外,我们建议使用@PostConstruct注解或指定 POJO 初始化方法。对于基于 XML 的配置元数据,可以使用init-method属性指定具有无效无参数签名的方法的名称

spring: 
  1. org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
  2. @Bean(initMethod = "")
JSR-250: 
  1. @PostConstruct

【Bean销毁】

官方使用建议建议您不要使用DisposableBean回调接口,因为它不必要地将代码耦合到 Spring。另外,我们建议使用@PreDestroy注解或指定 bean 定义支持的通用方法。使用基于 XML 的配置元数据时,可以在<bean/>上使用destroy-method属性

Spring: 
  1. org.springframework.beans.factory.DisposableBean#destroy()
  2. @Bean(destroyMethod = "")
JSR-250: 
  1. @PreDestroy

提示:

  1. destroy-method属性分配特殊的(inferred)值,该值指示 Spring 自动检测特定 bean 类上的公共closeshutdown方法。 (因此,实现java.lang.AutoCloseablejava.io.Closeable的任何类都将匹配.),在@Bean的注解中该属性默认的就是(inferred)
  2. 如果为同一个Bean配置了多个不同方法名的生命周期,则按照顺序执行,如果配置多个同名的生命周期,则只执行一次


【全局默认初始化和销毁方法】

此方式的优先级低于其他方式

<beans default-init-method="init" default-destroy-method="destroy" />

【上下文启动/关闭】

org.springframework.context.Lifecycle
org.springframework.context.LifecycleProcessor
org.springframework.context.SmartLifecycle

提示

  1. Lifecycle:需要在上下文中显示的调用才会通知
  2. LifecycleProcessor:会在上下文的生命周期中被自动调用
  3. SmartLifecycle:对特定 bean 的自动启动进行精细控制(包括启动阶段)

【获取ApplicationContext对象

实现:

  1. org.springframework.context.ApplicationContextAware
  2. 使用Bean的方式注入
  3. 【获取Bean在BeanFactory中的名称】

实现org.springframework.beans.factory.BeanNameAware

在填充常规 bean 属性之后但在初始化回调(例如InitializingBeanafterPropertiesSet或自定义 init-method)之前调用该回调


【其他Aware接口】

名字

作用

说明

BeanNameAware

获取Bean在BeanFactory中的名称

在填充常规 bean 属性之后但在初始化回调(例如InitializingBeanafterPropertiesSet或自定义 init-method)之前调用该回调

ApplicationEventPublisherAware

获取ApplicationEventPublisher对象

在填充常规 bean 属性之后但在初始化回调(例如InitializingBeanafterPropertiesSet或自定义 init-method)之前调用该回调

BeanClassLoaderAware


获取BeanFactory加载该Bean的类加载器

在填充常规 bean 属性之后但在初始化回调(例如InitializingBeanafterPropertiesSet或自定义 init-method)之前调用该回调

BeanFactoryAware

获取BeanFactory对象

在填充常规 bean 属性之后但在初始化回调(例如InitializingBeanafterPropertiesSet或自定义 init-method)之前调用该回调

LoadTimeWeaverAware

获取LoadTimeWeaver对象

在填充常规 bean 属性之后但在初始化回调(例如InitializingBeanafterPropertiesSet或自定义 init-method)之前,setApplicationContext

之后,调用该回调

MessageSourceAware

获取MessageSource对象

在填充常规 bean 属性之后但在初始化回调(例如InitializingBeanafterPropertiesSet或自定义 init-method)之前调用该回调

NotificationPublisherAware

Spring JMX 通知发布者


ResourceLoaderAware

已配置加载程序,用于对资源进行低级别访问

在填充常规 bean 属性之后但在ApplicationContextAware之前

ServletConfigAware

当前容器的配置,仅在Web程序中有效

在填充常规 bean 属性之后但在初始化回调(例如InitializingBeanafterPropertiesSet或自定义 init-method)之前调用该回调

ServletContextAware


当前容器的上下文,仅在Web程序中有效

在填充常规 bean 属性之后但在初始化回调(例如InitializingBeanafterPropertiesSet或自定义 init-method)之前调用该回调

举报

相关推荐

0 条评论