Spring中bean的生命周期

本文深入探讨Spring框架中Bean的生命周期,包括初始化前处理、属性设置、初始化方法调用及初始化后处理的详细流程。通过具体代码示例,展示如何利用InitializingBean接口和@BeanPostProcessor实现对Bean生命周期的自定义控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看官,直接先上个例子。
其中定义了init、destroy、afterPropertiesSet函数。

public class HelloWorld implements InitializingBean {
    String message;
    public String getMessage() {return message;}
    public void setMessage(String message) {this.message = message;}
    public void init(){System.out.println("helloworld  init函数");}
    public void destroy(){System.out.println("helloworld  destroy函数");}
	public void afterPropertiesSet() throws Exception {
        System.out.println("helloworld afterPropertiesSet");
    }
}

我在xml配置文件里面设置了init和destroy函数。

    <bean id="helloworld" class="com.learn.helloworld.HelloWorld"
          init-method="init" destroy-method="destroy">

注册每一个bean生命周期的钩子。

<bean class="com.learn.helloworld.InitHelloWorld"/>

相应的处理函数定义在了这里。


public class InitHelloWorld implements BeanPostProcessor{
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization:"+beanName);
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessAfterInitialization:"+beanName);
        return bean;
    }
}

最后,运行的结果是这样的。
在这里插入图片描述

分析

  可以看到,创建的时候,函数的运行顺序是这样的
postProcessBeforeInitialization(初始化之前) -> afterPropertiesSet(属性设置好) -> init(初始化函数) -> postProcessAfterInitialization(初始化之后)

  其次,BeanPostProcessor类对每个bean都钩。所以,钩完bean再钩下一个。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值