Spring IOC中bean的生命周期

Spring IOC 容器可以管理 Bean 的生命周期, Spring 允许在 Bean 生命周期的特定点执行定制的任务。

Spring IOC 容器中 Bean 的生命周期如下:
① 通过构造器或工厂方法创建 Bean 实例 : 调用构造器
② 为 Bean 的属性设置值和对其他 Bean 的引用 : 调用 setter
③ 将 将 Bean 给 实 例 传 递 给 Bean 后 置 处 理 器的postProcessBeforeInitialization 方法
④调用 Bean 的初始化方法 : init- - method
⑤将 将 Bean 给 实 例 传 递 给 Bean 后 置 处 理 器 的postProcessAfterInitialization 方法
⑥Bean 可以使用了
⑦ 当容器关闭时 , 调用 Bean 的销毁方法 : destroy- - method 。
Bean 的初始化和销毁方法:可以通过 bean 节点的 init-method 和destroy-method 来配置 Bean 的初始化方法和销毁方法:

<bean id="person" class="com.atguigu.spring.lifecycle.Person" init- - method="init" destroy- - method="destroy">
<property name="name" value="abcd"></property> 
</bean>

注意:ApplicationContext 接口中没有关闭容器的方法,所以使用
ApplicationContext 接口作为 IOC 容器的引用,destroy-method 将不会起到作 用 , 需 要 使 用 ApplicationContext 的 子 接 口
ConfigurableApplicationContext。
详解 Bean 后置处理器:
Bean 后置处理器 : Spring 提供的特殊的 Bean
①. Bean 后置处理器允许在调用初始化方法(即:bean 节点 init-method属性对应的方法的前后)前后对 Bean 进行额外的处理.
②. Bean 后置处理器对 IOC 容器里的所有 Bean 实例逐一处理, 而非单一
实例. 其典型应用是: 检查 Bean 属性的正确性或根据特定的标准更改 Bean的属性.
③. 对 Bean 后置处理器而言, 需要实现 BeanPostProcessor 接口

public class PersonPostProcessor implements BeanPostProcessor {
/** * arg0 : IOC 容器中 bean 的实例 * arg1 : IOC 容器中该 bean 的名字 * */ /
@Override
public Object postProcessAfterInitialization(Object arg0, String arg1)
throws BeansException {
if(arg0 instanceof Person){
System.out.println("postProcessAfterInitialization");
Person person = (Person) arg0;
String name =  person.getName();
if(!name.equals("AAAA")){
System.out.println("name 值必须为 AAAA!");
person.setName("AAAA");
} }
} }
return arg0;
} }
@Override
public Object postProcessBeforeInitialization(Object arg0, String arg1)
throws BeansExceptio n {
System.out.println("postProcessBeforeInitialization");
return arg0;
} }
} }

转载于:https://my.oschina.net/zhanghongbin01/blog/547725

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值