Spring Bean生命周期

本文详细介绍了Spring中Bean的生命周期,从实例化、属性设值、初始化、使用到销毁的过程,并通过代码示例展示了如何在XML配置中定义初始化和销毁回调方法。测试结果显示了各个步骤的执行顺序,为理解Spring Bean的生命周期提供了清晰的指导。
摘要由CSDN通过智能技术生成

简易过程

1.Bean实例化——调用无参构造器

2.Bean属性设值——调用Setter赋值

3.Bean初始化——调用init-method()

4.Bean使用

5.Bean销毁——调用destory-method()

完整过程

1.Bean实例化

2.Setter设值

3.setBeanName(),传入Bean当前的id值

4.setFactory(),传入当前 Factory 实例的引用

5.setApplicationContext(),传入当前 ApplicationContext 实例的引用

6.postProcessBeforeInitialzation() 后处理器在init-method()之前的操作

7.afterPropertiesSet()

8.init-method()完成初始化

9.postProcessAfterInitialization() 后处理在init-method()方法之后的操作

10.判断Bean的作用域

singleton放入loc容器的缓存池中,触发Spring对Bean的管理

prototype交给调用者管理

11.destory-method()销毁

Bean类代码如下

/**
 * 生命周期
 * 通过XML配置,实现初始化回调和销毁回调
 */
public class MyBean {
    //无参构造器
    public MyBean() {
        System.out.println("step1 执行无参构造创建bean实例");
    }

    private String name;

    //setter方法
    public void setName(String name) {
        this.name = name;
        System.out.println("step2 调用set方法完成属性设值");
    }

    //执行初始化方法
    public void initMehtod(){
        System.out.println("step3 执行初始化方法");
    }

    //执行销毁方法
    public void destroyMehtod(){
        System.out.println("step5 执行销毁方法");
    }

    @Override
    public String toString() {
        return "MyBean{" +
                "name='" + name + '\'' +
                '}';
    }
}

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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- bean生命周期 -->
    <!--通过XML配置-->
    <bean id="myBean" class="org.example.lifecycle.MyBean" init-method="initMehtod" destroy-method="destroyMehtod">
        <property name="name" value="zevin"/>
    </bean>
</beans>

 测试类

public class Test{
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/Beans.xml");
        MyBean myBean = (MyBean) context.getBean("myBean");
        System.out.println("step4 获取创建bean实例对象");
        System.out.println(myBean);
        //手动销毁Bean
        ((ClassPathXmlApplicationContext)context).close();
    }
}

结果如下

step1 执行无参构造创建bean实例
step2 调用set方法完成属性设值
step3 执行初始化方法

step4 获取创建bean实例对象

step5 执行销毁方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值