Spring中bean的生命周期

10 篇文章 0 订阅
3 篇文章 0 订阅

看官,直接先上个例子。
其中定义了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再钩下一个。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值