Spring-IOC-bean的生命周期

一、含义:bean从创建到销毁的过程。
二、bean的生命周期
(1)利用构造函数创建bean。
(2)利用set方法给bean注入属性。
(3)如果创建了前置处理器,则调用postProcessBeforeInitialization方法。
(4)调用bean的初始化方法。
(5)如果创建了后置处理器,则调用postProcessAfterInitialization方法。
(6)bean创建成功。
(7)当容器关闭时,调用bean的销毁方法。
三、具体实现
(1)创建类
User类

public class User {
    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        System.out.println("利用set方法给bean注入属性");
    }

    public User() {
        System.out.println("利用构造函数创建bean");
    }

    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }

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

    public void initMethod(){
        System.out.println("调用bean的初始化方法");
    }

    public void destoryMethod(){
        System.out.println("调用bean的销毁方法");
    }
}

后置处理器类MyBeanPostProcessor

public class MyBeanPostProcessor implements BeanPostProcessor {

    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("初始化前执行前置处理器中的postProcessBeforeInitialization方法");
        return null;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("初始化后执行后置处理器中的postProcessAfterInitialization方法");
        return null;
    }
}

(2)编写配置文件spring-config.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="user" class="com.wsh.pojo.User" init-method="initMethod" destroy-method="destoryMethod">
        <property name="name" value="张三"></property>
    </bean>

    <bean id="myBeanPostProcessor" class="com.wsh.pojo.MyBeanPostProcessor">

    </bean>
</beans>

(3)JAVA程序

    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        User user = context.getBean("user", User.class);
        ((ClassPathXmlApplicationContext)context).close();
    }

输出

利用构造函数创建bean
利用set方法给bean注入属性
初始化前执行前置处理器中的postProcessBeforeInitialization方法
调用bean的初始化方法
初始化后执行后置处理器中的postProcessAfterInitialization方法
调用bean的销毁方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值