谈谈我对Spring Bean 生命周期的理解

谈谈我对Spring Bean 生命周期的理解

https://www.jb51.net/article/136825.htm

Spring 中Bean的作用域及生命周期

https://cloud.tencent.com/developer/article/1377825

Spring Bean 的生命周期在整个 Spring 中占有很重要的位置,掌握这些可以加深对 Spring 的理解。这篇文章主要介绍了Spring Bean 生命周期,需要的朋友可以参考下

前言

Spring的ioc容器功能非常强大,负责Spring的Bean的创建和管理等功能。而Spring 的bean是整个Spring应用中很重要的一部分,了解Spring Bean的生命周期对我们了解整个spring框架会有很大的帮助。

BeanFactory和ApplicationContext是Spring两种很重要的容器,前者提供了最基本的依赖注入的支持,而后者在继承前者的基础进行了功能的拓展,例如增加了事件传播,资源访问和国际化的消息访问等功能。本文主要介绍了ApplicationContext和BeanFactory两种容器的Bean的生命周期。

首先看下生命周期图:

再谈生命周期之前有一点需要先明确:

Spring 只帮我们管理单例模式 Bean 的 完整 生命周期,对于 prototype 的 bean ,Spring 在创建好交给使用者之后则不会再管理后续的生命周期。

注解方式

在 bean 初始化时会经历几个阶段,首先可以使用注解 @PostConstruct , @PreDestroy 来在 bean 的创建和销毁阶段进行调用:

@Component
public class AnnotationBean {
  private final static Logger LOGGER = LoggerFactory.getLogger(AnnotationBean.class);
  @PostConstruct
  public void start(){
    LOGGER.info("AnnotationBean start");
  }
  @PreDestroy
  public void destroy(){
    LOGGER.info("AnnotationBean destroy");
  }
}

InitializingBean, DisposableBean 接口

还可以实现 InitializingBean,DisposableBean 这两个接口,也是在初始化以及销毁阶段调用:

@Service
public class SpringLifeCycleService implements InitializingBean,DisposableBean{
  private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycleService.class);
  @Override
  public void afterPropertiesSet() throws Exception {
    LOGGER.info("SpringLifeCycleService start");
  }
  @Override
  public void destroy() throws Exception {
    LOGGER.info("SpringLifeCycleService destroy");
  }
}

自定义初始化和销毁方法

也可以自定义方法用于在初始化、销毁阶段调用:

@Configuration
public class LifeCycleConfig {
  @Bean(initMethod = "start", destroyMethod = "destroy")
  public SpringLifeCycle create(){
    SpringLifeCycle springLifeCycle = new SpringLifeCycle() ;
    return springLifeCycle ;
  }
}
public class SpringLifeCycle{
  private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycle.class);
  public void start(){
    LOGGER.info("SpringLifeCycle start");
  }
  public void destroy(){
    LOGGER.info("SpringLifeCycle destroy");
  }
}

以上是在 SpringBoot 中可以这样配置,如果是原始的基于 XML 也是可以使用:

<bean class="com.crossoverjie.spring.SpringLifeCycle" init-method="start" destroy-method="destroy">
</bean>

来达到同样的效果。

实现 *Aware 接口

*Aware 接口可以用于在初始化 bean 时获得 Spring 中的一些对象,如获取 Spring 上下文 等。

@Component
public class SpringLifeCycleAware implements ApplicationContextAware {
  private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycleAware.class);
  private ApplicationContext applicationContext ;
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext ;
    LOGGER.info("SpringLifeCycleAware start");
  }
}

这样在 springLifeCycleAware 这个 bean 初始化会就会调用 setApplicationContext 方法,并可以获得 applicationContext 对象。

BeanPostProcessor 增强处理器

实现 BeanPostProcessor 接口,Spring 中所有 bean 在做初始化时都会调用该接口中的两个方法,可以用于对一些特殊的 bean 进行处理:

@Component
public class SpringLifeCycleProcessor implements BeanPostProcessor {
  private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycleProcessor.class);
  /**
   * 预初始化 初始化之前调用
   * @param bean
   * @param beanName
   * @return
   * @throws BeansException
   */
  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    if ("annotationBean".equals(beanName)){
      LOGGER.info("SpringLifeCycleProcessor start beanName={}",beanName);
    }
    return bean;
  }
  /**
   * 后初始化 bean 初始化完成调用
   * @param bean
   * @param beanName
   * @return
   * @throws BeansException
   */
  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if ("annotationBean".equals(beanName)){
      LOGGER.info("SpringLifeCycleProcessor end beanName={}",beanName);
    }
    return bean;
  }
}

执行之后观察结果:

018-03-21 00:40:24.856 [restartedMain] INFO c.c.s.p.SpringLifeCycleProcessor - SpringLifeCycleProcessor start beanName=annotationBean
2018-03-21 00:40:24.860 [restartedMain] INFO c.c.spring.annotation.AnnotationBean - AnnotationBean start
2018-03-21 00:40:24.861 [restartedMain] INFO c.c.s.p.SpringLifeCycleProcessor - SpringLifeCycleProcessor end beanName=annotationBean
2018-03-21 00:40:24.864 [restartedMain] INFO c.c.s.aware.SpringLifeCycleAware - SpringLifeCycleAware start
2018-03-21 00:40:24.867 [restartedMain] INFO c.c.s.service.SpringLifeCycleService - SpringLifeCycleService start
2018-03-21 00:40:24.887 [restartedMain] INFO c.c.spring.SpringLifeCycle - SpringLifeCycle start
2018-03-21 00:40:25.062 [restartedMain] INFO o.s.b.d.a.OptionalLiveReloadServer - LiveReload server is running on port 35729
2018-03-21 00:40:25.122 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - Registering beans for JMX exposure on startup
2018-03-21 00:40:25.140 [restartedMain] INFO com.crossoverjie.Application - Started Application in 2.309 seconds (JVM running for 3.681)
2018-03-21 00:40:25.143 [restartedMain] INFO com.crossoverjie.Application - start ok!
2018-03-21 00:40:25.153 [Thread-8] INFO o.s.c.a.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@3913adad: startup date [Wed Mar 21 00:40:23 CST 2018]; root of context hierarchy
2018-03-21 00:40:25.155 [Thread-8] INFO o.s.j.e.a.AnnotationMBeanExporter - Unregistering JMX-exposed beans on shutdown
2018-03-21 00:40:25.156 [Thread-8] INFO c.c.spring.SpringLifeCycle - SpringLifeCycle destroy
2018-03-21 00:40:25.156 [Thread-8] INFO c.c.s.service.SpringLifeCycleService - SpringLifeCycleService destroy
2018-03-21 00:40:25.156 [Thread-8] INFO c.c.spring.annotation.AnnotationBean - AnnotationBean destroy

直到 Spring 上下文销毁时则会调用自定义的销毁方法以及实现了 DisposableBean 的 destroy() 方法。

总结

以上所述是小编给大家介绍的Spring Bean 生命周期,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

 

Spring Bean对象的作用域:

在Spring容器中管理的Bean对象,可以在声明时通过scope属性或者相关注解指定其作用域

在Spring容器中,Bean对象的作用域一共有5种:singleton(单例模式)、prototype(原型模式)、request(HTTP请求)、session(会话)、global-session(全局会话)。

Bean的五种作用域

其中最常用的是singleton和prototype两种:

1)singleton(单例模式)

singleton是默认的作用域,当我们定义Bean时,如果没有给scope指定属性值,Spring会默认Bean的作用域为singleton。singleton属于单例模式,被singleton标识的对象具备全局唯一性,也就是在整个spring的容器中有且仅有一个该Bean的实例。

singleton的 配置文件如下:

<!-- 通过指定scope属性的值,来确定Bean的作用域 -->
<bean id="user" class="com.beans.User" 
   scope="singleton">
</bean>

2)prototype:这个作用域标识的对象每次获取调用都会创建新的对象

<!-- 通过指定scope属性的值,来确定Bean的作用域 -->
<bean id="user" class="com.beans.User" 
    scope="prototype">
</bean>

至于request(HTTP请求)、session(会话)、global-session(全局会话)三种作用域,用的话一般会配合SpringMVC框架进行使用,在这里不做深入了解;

Bean的生命周期

在Spring框架应用中,所有的Bean对象都有生命周期,就是指Bean对象的创建,初始化,服务,销毁的这个过程,我们称之为Bean对象的生命周期;

在Spring配置文件中,我们可以通过配置init-method,destory-method的属性来指定Bean的生命周期方法。

<!-- 比如连接池的配置 -->
<bean id="cPool" class="com.beans.ConnectionPool"
      scope="singleton"
      init-method="init"
      destroy-method="close">
</bean>

在链接池的配置中,我们可以为连接池指定由连接池提供的 init close 的方法来给连接池对象指定生命周期。

在Spring中Bean对象的销毁是由Bean对象的作用域的配置来决定的:

1、singleton 作用域的对象可以在容器关闭时会由Spring调用对象的销毁资源的方法来销毁Bean对象;

2、prototype 作用域的对象可以由容器创建对象,初始化对象,但Spring容器不负责销毁。

另外在Spring框架应用中,容器初始化时会默认构建所有由Spring管理的对象,但如果这些对象长时间不使用还占着内存就会造成一定的资源浪费,为了解决这个问题,Spring中还提供了一种延时加载机制,以此来提高系统资源的有效使用。

Spring 中的延时加载有两种方式:

1)在bean元素中将 lazy-init 属性的值设为 false,这种方式只对当前设置的单个bean元素有效:

<!-- 例如连接池的延时加载设置 -->
<bean id="cPool" class="com.beans.ConnectionPool"
      scope="singleton"
      init-method="init"
      destroy-method="close"
      lazy-init="false">
</bean>

2)在beans元素中将 default-lazy-init 属性的值设为 true ,这种方式用于指定 beans 标签中所有 bean 的延时加载策略。例如:

<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
    xmlns="http://www.springframework.org/schema/beans" 
    xsi:schemaLocation="  
       http://www.springframework.org/schema/beans   
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
       
    <bean id="cPool" 
			class="com.beans.ConnectionPool" 
			scope="singleton" 
			init-method="init" 
			destroy-method="destroy">
	 </bean>
	
</beans>
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值