Spring Bean的生命周期

  这篇文章里主要回顾Spring里Bean的生命周期,并通过一个例子来验证其生命周期。


Bean生命周期:

  1. Spring调用bean构造器,创建实例对象;
  2. Spring调用bean的setXxx()方法,将属性注入进该bean;
  3. 如果bean实现了BeanNameAware接口,则调用执行setBeanName(String beanId)方法;
  4. 如果bean实现了BeanFactoryAware接口,则调用执行setBeanFactory(BeanFactory factory)方法;
  5. 如果该bean实现了ApplicationContextAware这个接口,则Spring此时会调用执行setApplicationContext(ApplicationContext arg0)方法;
  6. 如果容器注册了BeanPostProcessor的实现类(注意这里是容器,而不是bean),则调用执行postProcessBeforeInitialization(Object bean, String beanName)方法;
  7. 如果bean实现了InitializingBean接口,Spring将调用afterPropertiesSet()方法;
  8. 如果bean在配置文件里配置了init-method属性,则执行init-method指定的方法;
  9. 如果容器注册了BeanPostProcessor的实现类(注意这里是容器,而不是bean),则调用执行postProcessorAfterInitialization(Object bean, String beanName)方法;
  10. 此时,bean的初始化准备就绪,可以被应用程序使用了,下面的例子里在Main主类里调用Service bean的业务方法service();
  11. 如果bean实现了DisposableBean接口,Spring将调用destroy()方法;
  12. 如果bean在配置文件里配置了destroy-method属性,则执行destroy-method指定的方法。

代码验证:
接口:

public interface IService {

}

接口实现类:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class Service implements IService, BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean{

    private String service;

    public Service(){
        System.out.println("Constructor:构造器方法");
    }

    public void setService(String arg0){
        this.service = arg0;
        System.out.println("setXxx:setService方法");
    }

    @Override
    public void setBeanName(String name) {
        // TODO Auto-generated method stub
        System.out.println("BeanNameAware:setBeanName方法");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        // TODO Auto-generated method stub
        System.out.println("BeanFactoryAware:setBeanFactory方法");
    }

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        // TODO Auto-generated method stub
    System.out.println("ApplicationContextAware:setApplicationContext方法");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // TODO Auto-generated method stub
    System.out.println("InitializingBean:afterPropertiesSet");
    }

    public void serviceInit(){
        System.out.println("init-method:serviceInit");
    }

    public void service(){
        System.out.println("service:业务方法");
    }

    @Override
    public void destroy() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("DisposableBean:destroy");
    }

    public void serviceDestroy(){
        System.out.println("destroy-method:serviceDestroy");
    }

}

Bean后处理器类

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // TODO Auto-generated method stub
        System.out.println("BeanPostProcessor:bean后处理器before方法");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("BeanPostProcessor:bean后处理器after方法");
        return bean;
    }

}

配置文件:config.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-3.2.xsd">

    <bean id="service" class="bean.lifecycle.Service" init-method="serviceInit" destroy-method="serviceDestroy">
        <property name="service" value="service"></property>
    </bean>

    <bean class="bean.lifecycle.MyBeanPostProcessor"/>
</beans>

主类:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config.xml");
        Service service = (Service)ac.getBean("service");
        service.service();
        ((ClassPathXmlApplicationContext)ac).close();

    }
}

代码运行结果:

Constructor:构造器方法
setXxx:setService方法
BeanNameAware:setBeanName方法
BeanFactoryAware:setBeanFactory方法
ApplicationContextAware:setApplicationContext方法
BeanPostProcessor:bean后处理器before方法
InitializingBean:afterPropertiesSet
init-method:serviceInit
BeanPostProcessor:bean后处理器after方法
service:业务方法
DisposableBean:destroy
destroy-method:serviceDestroy

  这段代码有几个需要注意的地方:

  1. BeanPostProcessor必须由另一个类实现,不能由Service类实现,否则的话,容器启动时并不会执行BeanPostProcessor里的两个方法,也就是说BeanPostProcessor的实现类所影响的范围是容器里没有实现BeanPostProcessor接口的类;
  2. ApplicationContext接口里并没有定义close()方法,但是其实现类里有这个方法,用来关闭容器,容器里的bean直到该容器应用上下文销毁才会被销毁。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring生命周期包括实例化、配置和销毁三个阶段。首先,实例化阶段是指创建一个Bean的实例。在Spring中,Bean的实例化可以通过使用BeanFactory或ApplicationContext来获取。其次,配置阶段是指对实例化的Bean进行配置,也就是进行IOC注入。在这个阶段,Spring会根据配置文件中的Bean的id值进行相应的配置。如果Bean实现了BeanNameAware接口,Spring还会调用它实现的setBeanName(String)方法,传递的参数就是Bean的id值。最后,销毁阶段是指当Bean不再使用时进行垃圾回收。对于Singleton模式的Bean,Spring会负责管理整个生命周期;而对于Prototype模式的Bean,Spring在创建好并交给使用者后就不再管理后续的生命周期。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [关于Spring Bean的生命周期](https://blog.csdn.net/Apeopl/article/details/82964799)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Springbean生命周期详解](https://blog.csdn.net/qq_64169170/article/details/123052663)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值