SpringBean生命周期详解

r囧r小猫 2022-05-25 03:48 385阅读 0赞

在Spring中 Bean 可谓是一个核心的元素,当我们结合Spring进行编程的时候也离不开Bean,面对这样重要的一个角色,了解其生命周期和该生命周期所涉及的环节对我们更加熟练灵活地使用Bean是很有Bean必要的,下面我们就来详细分析下Bean的生命周期吧。

生命周期流程图

  我们先通过一个流程图,对Bean的生命周期先做一个整体的认识和了解。

20180507183953201

若容器实现了流程图中涉及的接口,程序将按照以上流程进行。需要我们注意的是,这些接口并不是必须实现的,可根据自己开发中的需要灵活地进行选择,没有实现相关接口时,将略去流程图中的相关步骤。

接口方法的分类

  上面流程图当中涉及调用很多的方法,可能我们直接去理解和记忆比较困难,其实对于这么一大堆方法我们可以根据它们的特点对他们进行整理分类,下面提供一种可供大家参考的分类模型:






















分类类型 所包含方法
Bean自身的方法 配置文件中的init-method和destroy-method配置的方法、Bean对象自己调用的方法
Bean级生命周期接口方法 BeanNameAware、BeanFactoryAware、InitializingBean、DiposableBean等接口中的方法
容器级生命周期接口方法 InstantiationAwareBeanPostProcessor、BeanPostProcessor等后置处理器实现类中重写的方法

  这时回过头再来看这些方法轮廓上就比较清晰了,记忆的时候我们可通过记忆分类的类型来理解性的记忆所涉及的方法。

编程实践

  有了上面的理论分析,我们再来通过编程实践来验证下我们的结论,顺便进一步加深我们对整个生命周期的理解。

准备工作

编写测试Bean

  我们先编写一个测试Bean来实现流程图中的相关接口.
   StudentBean.java

  1. package com.yanxiao.cyclelife;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.BeanFactory;
  4. import org.springframework.beans.factory.BeanFactoryAware;
  5. import org.springframework.beans.factory.BeanNameAware;
  6. import org.springframework.beans.factory.DisposableBean;
  7. import org.springframework.beans.factory.InitializingBean;
  8. /**
  9. * 测试生命周期的Bean
  10. * Created by yanxiao on 2016/8/1.
  11. */
  12. public class StudentBean implements InitializingBean, DisposableBean, BeanNameAware, BeanFactoryAware {
  13. private String name;
  14. private int age;
  15. private String beanName;//实现了BeanNameAware接口,Spring可以将BeanName注入该属性中
  16. private BeanFactory beanFactory;//实现了BeanFactory接口,Spring可将BeanFactory注入该属性中
  17. public StudentBean(){
  18. System.out.println("【Bean构造方法】学生类的无参构造方法");
  19. }
  20. @Override
  21. public String toString() {
  22. return "StudentBean{" +
  23. "name='" + name + '\'' +
  24. ", age=" + age +
  25. ", beanName='" + beanName + '\'' +
  26. '}';
  27. }
  28. public String getName() {
  29. return name;
  30. }
  31. public void setName(String name) {
  32. System.out.println("【set注入】注入学生的name属性");
  33. this.name = name;
  34. }
  35. public int getAge() {
  36. return age;
  37. }
  38. public void setAge(int age) {
  39. System.out.println("【set注入】注入学生的age属性");
  40. this.age = age;
  41. }
  42. /**
  43. * 自己编写的初始化方法
  44. */
  45. public void myInit(){
  46. System.out.println("【init-method】调用init-method属性配置的初始化方法");
  47. }
  48. /**
  49. * 自己编写的销毁方法
  50. */
  51. public void myDestroy(){
  52. System.out.println("【destroy-method】调用destroy-method属性配置的销毁方法");
  53. }
  54. /**
  55. * BeanFactoryAware接口的方法
  56. * @param beanFactory
  57. * @throws BeansException
  58. */
  59. @Override
  60. public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
  61. this.beanFactory = beanFactory;
  62. System.out.println("【BeanFactoryAware接口】调用BeanFactoryAware的setBeanFactory方法得到beanFactory引用");
  63. }
  64. /**
  65. * BeanNameAware接口的方法
  66. * @param name
  67. */
  68. @Override
  69. public void setBeanName(String name) {
  70. this.beanName = name;
  71. System.out.println("【BeanNameAware接口】调用BeanNameAware的setBeanName方法得到Bean的名称");
  72. }
  73. /**
  74. * InitializingBean接口的方法
  75. * @throws Exception
  76. */
  77. @Override
  78. public void afterPropertiesSet() throws Exception {
  79. System.out.println("【InitializingBean接口】调用InitializingBean接口的afterPropertiesSet方法");
  80. }
  81. /**
  82. * DisposableBean接口的方法
  83. * @throws Exception
  84. */
  85. @Override
  86. public void destroy() throws Exception {
  87. System.out.println("【DisposableBean接口】调用DisposableBean接口的destroy方法");
  88. }
  89. }

上面代码中的 myInit() 和 ·myDestroy()· 方法供我们在配置文件中通过init-method和destroy-method属性进行指定。

实现BeanPostProcessor接口

  我们编写BeanPostProcessor接口的一个实现类: MyBeanPostProcessor.java

  1. package com.yanxiao.cyclelife;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.config.BeanPostProcessor;
  4. /**
  5. * Created by yanxiao on 2016/8/1.
  6. */
  7. public class MyBeanPostProcessor implements BeanPostProcessor {
  8. public MyBeanPostProcessor(){
  9. System.out.println("【BeanPostProcessor接口】调用BeanPostProcessor的构造方法");
  10. }
  11. @Override
  12. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  13. System.out.println("【BeanPostProcessor接口】调用postProcessBeforeInitialization方法,这里可对"+beanName+"的属性进行更改。");
  14. return bean;
  15. }
  16. @Override
  17. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  18. System.out.println("【BeanPostProcessor接口】调用postProcessAfterInitialization方法,这里可对"+beanName+"的属性进行更改。");
  19. return bean;
  20. }
  21. }

实现BeanPostProcessor接口

  编写BeanPostProcessor接口的一个实现类 MyBeanPostProcessor.java

  1. package com.yanxiao.cyclelife;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.config.BeanPostProcessor;
  4. /**
  5. * Created by yanxiao on 2016/8/1.
  6. */
  7. public class MyBeanPostProcessor implements BeanPostProcessor {
  8. public MyBeanPostProcessor(){
  9. System.out.println("【BeanPostProcessor接口】调用BeanPostProcessor的构造方法");
  10. }
  11. @Override
  12. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  13. System.out.println("【BeanPostProcessor接口】调用postProcessBeforeInitialization方法,这里可对"+beanName+"的属性进行更改。");
  14. return bean;
  15. }
  16. @Override
  17. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  18. System.out.println("【BeanPostProcessor接口】调用postProcessAfterInitialization方法,这里可对"+beanName+"的属性进行更改。");
  19. return bean;
  20. }
  21. }

实现InstantiationAwareBeanPostProcessor接口

  实现InstantiationAwareBeanPostProcessor接口,为了编程方便我们直接通过继承Spring中已经提供的一个实现了该接口的适配器类InstantiationAwareBeanPostProcessorAdapter来进行测试。

MyInstantiationAwareBeanPostProcessor.java

  1. package com.yanxiao.cyclelife;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.PropertyValues;
  4. import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
  5. import java.beans.PropertyDescriptor;
  6. /**
  7. * 一般情况下,当我们需要实现InstantiationAwareBeanPostProcessor接口时,是通过继承Spring框架中InstantiationAwareBeanPostProcessor接口实现类
  8. * InstantiationAwareBeanPostProcessorAdapter这个适配器类来简化我们实现接口的工作
  9. * Created by yanxiao on 2016/8/1.
  10. */
  11. public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {
  12. public MyInstantiationAwareBeanPostProcessor() {
  13. System.out.println("【InstantiationAwareBeanPostProcessor接口】调用InstantiationAwareBeanPostProcessor构造方法");
  14. }
  15. /**
  16. * 实例化Bean之前调用
  17. */
  18. @Override
  19. public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException {
  20. System.out.println("【InstantiationAwareBeanPostProcessor接口】调用InstantiationAwareBeanPostProcessor接口的postProcessBeforeInstantiation方法");
  21. return null;
  22. }
  23. /**
  24. * 实例化Bean之后调用
  25. */
  26. @Override
  27. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  28. System.out.println("【InstantiationAwareBeanPostProcessor接口】调用InstantiationAwareBeanPostProcessor接口的postProcessAfterInitialization方法");
  29. return bean;
  30. }
  31. /**
  32. * 设置某个属性时调用
  33. */
  34. @Override
  35. public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)
  36. throws BeansException {
  37. System.out.println("【InstantiationAwareBeanPostProcessor接口】调用InstantiationAwareBeanPostProcessor接口的postProcessPropertyValues方法");
  38. return pvs;
  39. }
  40. }

BeanFactoryPostProcessor接口

  我们编写BeanFactoryPostProcessor接口的一个实现类 BeanFactoryPostProcessor.java

  1. package com.yanxiao.cyclelife;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.config.BeanDefinition;
  4. import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
  5. import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
  6. /**
  7. * Created by yanxiao on 2016/8/1.
  8. */
  9. public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
  10. public MyBeanFactoryPostProcessor() {
  11. System.out.println("【BeanFactoryPostProcessor接口】调用BeanFactoryPostProcessor实现类构造方法");
  12. }
  13. /**
  14. * 重写BeanFactoryPostProcessor接口的postProcessBeanFactory方法,可通过该方法对beanFactory进行设置
  15. */
  16. @Override
  17. public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
  18. throws BeansException {
  19. System.out.println("【BeanFactoryPostProcessor接口】调用BeanFactoryPostProcessor接口的postProcessBeanFactory方法");
  20. BeanDefinition beanDefinition = beanFactory.getBeanDefinition("studentBean");
  21. beanDefinition.getPropertyValues().addPropertyValue("age", "21");
  22. }
  23. }

编写Spring配置文件beans.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
  8. <!--配置Bean的后置处理器-->
  9. <bean id="beanPostProcessor" class="com.yanxiao.cyclelife.MyBeanPostProcessor">
  10. </bean>
  11. <!--配置instantiationAwareBeanPostProcessor-->
  12. <bean id="instantiationAwareBeanPostProcessor" class="com.yanxiao.cyclelife.MyInstantiationAwareBeanPostProcessor">
  13. </bean>
  14. <!--配置BeanFactory的后置处理器-->
  15. <bean id="beanFactoryPostProcessor" class="com.yanxiao.cyclelife.MyBeanFactoryPostProcessor">
  16. </bean>
  17. <bean id="studentBean" class="com.yanxiao.cyclelife.StudentBean" init-method="myInit"
  18. destroy-method="myDestroy" scope="singleton">
  19. <property name="name" value="yanxiao"></property>
  20. <property name="age" value="21"></property>
  21. </bean>
  22. </beans>

进行测试

  通过上面的准备工作我们已经把相关的类和测试文件编写完毕,下面我们就通过测试代码来验证我们的成果。

  1. package com.yanxiao.cyclelife;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. /**
  5. * Created by yanxiao on 2016/8/1.
  6. */
  7. public class TestCyclelife {
  8. public static void main(String[] args){
  9. System.out.println("--------------【初始化容器】---------------");
  10. ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/beans1.xml");
  11. System.out.println("-------------------【容器初始化成功】------------------");
  12. //得到studentBean,并显示其信息
  13. StudentBean studentBean = context.getBean("studentBean",StudentBean.class);
  14. System.out.println(studentBean);
  15. System.out.println("--------------------【销毁容器】----------------------");
  16. ((ClassPathXmlApplicationContext)context).registerShutdownHook();
  17. }
  18. }

测试结果

这里写图片描述

发表评论

表情:
评论列表 (有 0 条评论,385人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBean生命周期详解

    在Spring中 Bean 可谓是一个核心的元素,当我们结合Spring进行编程的时候也离不开Bean,面对这样重要的一个角色,了解其生命周期和该生命周期所涉及的环节对我们更加