Spring bean生命周期

Spring bean生命周期主要分7个周期:

  1. 通过构造器创建bean实例
  2. bean中注入属性
  3. bean的实例传递给后置处理器
  4. 初始化bean(需要配置初始化的方法)
  5. bean的实例传递给后置处理器
  6. 可以使用bean
  7. 销毁bean(需要配置销毁的方法)

下面测试一下:

一、Test bean:

public class TestBeanLife {
    private String id;
    private String name;

    public TestBeanLife(){
        System.out.println("第一步,通过构造器创建bean实例");
    }

    public void setId(String id) {
        System.out.println("第二步,向bean中注入属性");
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void init_method(){
        System.out.println("第四步,初始化bean(需要配置初始化的方法)");
    }

    public void destroy_method(){
        System.out.println("第七步,销毁bean(需要配置销毁的方法)");
    }
}

二、后置处理器:

public class HouZhi implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("第三步,把bean的实例传递给后置处理器"+"---"+bean);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("第五步,把bean的实例传递给后置处理器"+"---"+bean);
        return bean;
    }
}

三、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="beanLife" class="cn.kexing.beanLife.TestBeanLife" init-method="init_method" destroy-method="destroy_method">
    <property name="id" value="11111111"></property>
    <property name="name" value="张三"></property>
</bean>

<!--    后置处理器-->
    <bean id="houzhi" class="cn.kexing.beanLife.HouZhi"></bean>
</beans>

四、Test

    @Test
    //测试bean的生命周期
    public void testBeanLife(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean8.xml");
        TestBeanLife beanLife = context.getBean("beanLife",TestBeanLife.class);
        System.out.println("第六步,可以使用bean");
        System.out.println(beanLife);
        //需手动销毁
        context.close();
    }

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值