(六)Bean的生命周期

  1. 通过构造器创建实例
  2. 为Bean的属性设置值。(调用Set方法)
  3. 调用Bean初始化的方法(需要自己配置)
  4. 对象可以使用(获取对象)
  5. 当容器关闭是,调用bean的销毁的方法(需要自己配置)
    实例验证,通过在相应方法中设置输出。
    创建类并为对应方法设置输出
public class Time {
//构造方法
    public Time() {
        System.out.println("The first step");
    }

    private String time;

    public void setTime(String time) {
        this.time = time;
        System.out.println("The second:为Bean注入属性");
    }
//初始化方法,需要配置
    public void initMethod(){
        System.out.println("The third");
    }
//销毁方法,需要配置
    public void destroyMethod(){
        System.out.println("The fifth");
    }
}

配置XML文件
通过Bean标签中的init-method属性与destroy-method属性设置初始化方法与销毁方法。

<bean id="beanTime" class="com.cjy.beanTime.Time" init-method="initMethod" destroy-method="destroyMethod">
        <property name="time" value="15:02"> </property>
    </bean>

验证输出结果

public void testBeanTime(){
        ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("beanTime.xml");
        System.out.println("The four:获取对象");
        Time time= context.getBean("beanTime", Time.class);
        context.close();
    }

在这里插入图片描述
生命周期中除了这基本的五步,还可以添加后置处理器,在初始化之前会对Bean进行处理,在初始化之后也会对Bean实例进行处理,使得生命周期变为七步。
创建后置处理器

public class MyBeanPost implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("After Postprocess");
        return null;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("Before Postprocess");
        return null;
    }
}

在XML中配置后置处理器
在Bean的创建过程可以添加多个后置处理器,Bean创建过程中,同一个XML文件中配置的后置处理器都会运行。

<bean id="beanTime" class="com.cjy.beanTime.Time" init-method="initMethod" destroy-method="destroyMethod">
        <property name="time" value="15:02"> </property>
    </bean>
    <bean id="post" class="com.cjy.beanTime.MyBeanPost"> </bean>

验证结果

public void testBeanTime(){
        ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("beanTime.xml");
        System.out.println("The four:获取对象");
        Time time= context.getBean("beanTime", Time.class);
        context.close();
    }

在这里插入图片描述
可以看到,多了两步。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值