(七)SpringIOC容器中bean生命周期

SpringIOC容器可以管理Bean的生命周期Spring允许在Bean生命周期的特定点执行定制任务。
SpringIOC容器对Bean的生命周期进行管理的过程:
1.通过构造器或工厂方法创建Bean实例
2.为Bean的属性设置值和对其他Bean的引用
3.调用Bean的初始化方法
4.Bean可以使用了
5.当容器关闭时,调用Bean 的销毁方法
第一步:配置xml文件
<这里写代码片?xml version=”1.0” encoding=”UTF-8”?>

package com.atguigu.spring.beans.cycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object  bean, String beanName)
            throws BeansException {
        //postProcess是处理所有bean的所以处理时要进行过滤
        System.out.println("postProcessBeforeInitialization:"+bean+","+beanName);
        //Car car=new Car();
        //if("car".equals(beanName)){   
        //car.setBrand("ford"); 
        //}
        return bean;
    }
    //初始化之后执行该方法
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName)
                throws BeansException {
            System.out.println("postProcessAfterInitialization:"+bean+","+beanName);
            Car car=new Car();
            car.setBrand("ford");
            return car;
        }

}

第三步:新建bean类

public class Car {
    public Car(){
        System.out.println("Car's Constructor....");
    }
    private String brand;
    public void setBrand(String brand){
        System.out.println("setBrand...");
        this.brand=brand;
    }
    public void init2(){
        System.out.println("init.....");
    }
    public void destroy(){
        System.out.println("destroy.....");
    }
    @Override
    public String toString() {
        return "Car [brand=" + brand + "]";
    }

}

第四步:执行main方法

package com.atguigu.spring.beans.cycle;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans-cycle.xml");
        Car car=(Car) ctx.getBean("car");
        System.out.println("tostring:"+car);
        //关闭IOC容器
        ctx.close();        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值