首页 > 其他分享 >Spring之bean的七步生命周期

Spring之bean的七步生命周期

时间:2023-01-08 16:35:23浏览次数:47  
标签:name Spring System 七步 String bean public out

bean的七步生命周期
(1)调用无参数构造方法创造bean实例
(2)调用set方法对bean的属性及其他bean的引用属性进行设置
(3)把bean实例传递给bean的后置处理器方法postProcessBeforeInitialization()
(4)调用bean的初始化方法initMethod()
(5)把bean实例传递给bean的后置处理器方法postProcessAfterInitialization()
(6)获取创建bean的实例对象进行使用
(7)当容器关闭时,调用bean的初始化方法destroyMethod()
代码演示:
(1)首先,创建一个类

MyBeanLifeCycle
public class MyBeanLifeCycle {
    private String name;

    public MyBeanLifeCycle() {
        System.out.println("第一步,执行无参构造方法创造bean实例");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        System.out.println("第二步,执行set方法对bean的属性进行设置");
    }
    public void initMethod(){
        System.out.println("第四步,执行bean的初始化方法");
    }
    public void destroyMethod(){
        System.out.println("第七步,容器关闭了执行bean的销毁方法");
    }

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

(2)创建一个类实现接口 BeanPostProcessor,创建后置处理器

MyBeanPost
public class MyBeanPost implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("第三步,在初始化方法之前执行的后置处理器方法");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("第五步,在初始化方法之后执行的后置处理器方法");
        return bean;
    }
}

(3)对spring的xml文件进行配置

bean1.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="myBeanLifeCycle" class="cn.com.spring.lifecycle.MyBeanLifeCycle"
          init-method="initMethod" destroy-method="destroyMethod">
        <property name="name" value="小猪"> </property>
    </bean>
    <bean id="myBeanPost" class="cn.com.spring.lifecycle.MyBeanPost"> </bean>
</beans>

(4)测试

测试代码
public class MainApp {
    public static void main(String[] args) {
        //加载配置文件,获取ClassPathXmlApplicationContext容器
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        //获取bean的实例对象
        MyBeanLifeCycle myBeanLifeCycle = context.getBean("myBeanLifeCycle", MyBeanLifeCycle.class);
        System.out.println("第六步,获取创建bean的实例对象---->"+myBeanLifeCycle);
        //手动让bean实例进行销毁
        context.close();

    }
}

运行结果:

标签:name,Spring,System,七步,String,bean,public,out
From: https://www.cnblogs.com/onecodepig/p/17034817.html

相关文章