SpringBean生命周期详解

SpringBean生命周期详解SpringBean生命周期详解一、简述:Spring是我们每天都在使用的框架,Bean是被Spring管理的Java对象,是Spring框架最重要的部分之一,那么让我们一起了解一下Spring中Bean的生命周期是怎样的吧二、流程图我们先从宏观的角度看一下Spring的生命周期:![在这里插入图片描述](https://img-blog.csdnimg.cn/20201028174058916.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5

大家好,欢迎来到IT知识分享网。

SpringBean生命周期详解

一、简述:

Spring是我们每天都在使用的框架,Bean是被Spring管理的Java对象,是Spring框架最重要的部分之一,那么让我们一起了解一下Spring中Bean的生命周期是怎样的吧

二、流程图

在这里插入图片描述

总体分为四个阶段:

  ①实例化 CreateBeanInstance
  ②属性赋值 PopulateBean
  ③初始化 Initialization
  ④销毁 Destruction**

其中多个增强接口贯穿了这四个阶段!

三、SpringBean生命周期中的增强接口PostProcessor:

在上图里有多种后置处理器接口,它们贯穿了Bean的生命周期,且它们的实现类都会在SpringIOC容器进行初始化的时候进行实例化,让我们来做一个区分:

|  |  ||--|--||  |  |

解释:

Bean的实例化:
是指Spring通过反射获取Bean的构造方法进行实例化的过程
Bean的初始化:
是指Bean的属性赋值、执行初始化方法(init-method)的过程

四、实例展示

SpringBeanDemo

package com.rx.spring;
 
import com.rx.spring.domain.Person;
import com.rx.spring.domain.Student;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
public class SpringBeanDemo { 
   
    public static void main(String[] args) throws Exception { 
   
        System.out.println("****开始启动****");
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
        System.out.println("****启动完毕****");
        Person person = applicationContext.getBean("person", Person.class);
        Student student = applicationContext.getBean("student", Student.class);
 
        System.out.println("=============================================");
        System.out.println("person:" + person);
        System.out.println("student:" + student);
        person.destroy();
 
        System.out.println("============现在开始关闭容器======================");
        applicationContext.registerShutdownHook();
    }
}

Config

package com.rx.spring;
 
import org.springframework.context.annotation.*;
 
@Configuration
@ComponentScan("com.rx.spring")
@ImportResource("classpath:spring.xml")
public class Config { 
   
     
}

Person

package com.rx.spring.domain;
 
import lombok.Data;
import org.springframework.beans.factory.DisposableBean;
 
@Data
public class Person implements DisposableBean { 
   
    private String name;
    private String address;
    private String tel;
 
    public Person(String name, String address, String tel) { 
   
        System.out.println("Person--->>>有参构造方法");
        this.name = name;
        this.address = address;
        this.tel = tel;
    }
 
    public Person() { 
   
        System.out.println("Person--->>>无参构造方法");
    }
 
    private void raoInitMethod() { 
   
        System.out.println("person--->>>InitMethod...");
    }
 
    private void raoDestroyMethod() { 
   
        System.out.println("person--->>>DestroyMethod...");
    }
 
    @Override
    public void destroy() throws Exception { 
   
        System.out.println("【DisposableBean接口】调用DisposableBean.destroy()");
    }
}

Student

package com.rx.spring.domain;
 
import lombok.Data;
import org.springframework.beans.factory.DisposableBean;
 
@Data
public class Student implements DisposableBean { 
   
    private String username;
    private String password;
 
    public Student(String username, String password) { 
   
        System.out.println("student--->>有参构造方法");
        this.username = username;
        this.password = password;
    }
    public Student() { 
   
        System.out.println("student--->>>无参构造方法");
    }
 
    private void raoInitMethod() { 
   
        System.out.println("student--->>>InitMethod...");
    }
 
    private void raoDestroyMethod() { 
   
        System.out.println("student--->>>DestroyMethod...");
    }
 
    @Override
    public void destroy() throws Exception { 
   
        System.out.println("【DisposableBean接口】调用DisposableBean.destroy()");
    }
}

RaoBeanFactoryPostProcessor

package com.rx.spring.beanfactorypostprocessor;
 
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
 
@Component
public class RaoBeanFactoryPostProcessor implements BeanFactoryPostProcessor { 
   
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { 
   
        System.out.println("postProcessBeanFactory...");
        String[] beanStr = beanFactory.getBeanDefinitionNames();
        for (String beanName : beanStr) { 
   
            if ("person".equals(beanName)) { 
   
                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
                MutablePropertyValues m = beanDefinition.getPropertyValues();
                if (m.contains("address")) { 
   
                    //这个方法是判断是否有propertyName=username,有就替换,没有就添加
                    m.addPropertyValue("address", "大兴区");
                    System.out.println("***修改了address属性初始值了***");
                }
            }
        }
    }
}

RaoInstantiationAwareBeanPostProcessor

package com.rx.spring.beanpostprocessor;
 
import com.rx.spring.domain.Person;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import org.springframework.stereotype.Component;
 
@Component
public class RaoInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter { 
   
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException { 
   
        if ("person".equals(beanName) || "student".equals(beanName)) { 
   
            System.out.println(beanName + "--->>>InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation....");
        }
        return null;
    }
 
    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { 
   
        if ("person".equals(beanName) || "student".equals(beanName)) { 
   
            System.out.println(beanName + "--->>>InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation....");
        }
        return bean instanceof Person;
    }
 
    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException { 
   
        System.out.println(beanName + "--->>>InstantiationAwareBeanPostProcessor.postProcessProperties...");
        PropertyValue[] propertyValues = pvs.getPropertyValues();
        for (PropertyValue propertyValue : propertyValues) { 
   
            if ("name".equals(propertyValue.getName())) { 
   
                propertyValue.setConvertedValue("改后rx");
            }
        }
        return pvs;
    }
}

RaoBeanPostProcessor


package com.rx.spring.beanpostprocessor;
 
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
 
@Component
public class RaoBeanPostProcessor implements BeanPostProcessor { 
   
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 
   
        if ("person".equals(beanName) || "student".equals(beanName)) { 
   
            System.out.println(beanName + "--->>>BeanPostProcessor.postProcessBeforeInitialization...");
        }
        return bean;
    }
 
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 
   
        if ("person".equals(beanName) || "student".equals(beanName)) { 
   
            System.out.println(beanName + "--->>>BeanPostProcessor.postProcessAfterInitialization....");
        }
        return bean;
    }
}

spring.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
    <bean id ="person" class="com.rx.spring.domain.Person" init-method="raoInitMethod" destroy-method="raoDestroyMethod">
        <property name="name" value="rx"/>
        <property name="address" value="beijing"/>
        <property name="tel" value="157********"/>
    </bean>
 
    <bean id ="student" class="com.rx.spring.domain.Student" init-method="raoInitMethod" destroy-method="raoDestroyMethod">
        <property name="username" value="rx"/>
        <property name="password" value="1234"/>
    </bean>
 
</beans>

运行结果:

在这里插入图片描述
在这里插入图片描述

运行结果符合预期,成功验证了之前的结论!!!

原创不易,转载请附上本页面链接

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/14641.html

(0)
上一篇 2024-02-25 11:00
下一篇 2024-02-27 08:26

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信