spring(11) Spring的生命周期

Spring Ioc容器对Bean的生命周期进行管理的过程:

1)通过构造器或工厂方法创建Bean实例

2)为Bean的属性设置值和对其他Bean的引用

3)调用Bean的初始化方法

4)Bean可以使用了

5)当容器关闭时,调用Bean的销毁方法。

在Bean的声明里设置init-method和destroy-method属性,为Bean指定初始化和销毁方法。

示例代码:

package bean.cycle;
 
public class Car {
private String name;
 
public void setName(String name) {
System.out.println("setName...");
this.name = name;
}
 
public Car() {
System.out.println("Constructor...");
}
 
public void init() {
System.out.println("init...");
}
 
public void destroy() {
System.out.println("destroy...");
}
 
@Override
public String toString() {
return "Car [name=" + name + "]";
}
}

<bean id="car" class="bean.cycle.Car" p:name="Baoma" init-method="init" destroy-method="destroy"/>

package bean.cycle;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class Main {
 
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-cycle.xml");
Car car = (Car) ctx.getBean("car");
System.out.println(car);
car.destroy();
}
}
 

 

执行结果如图:

 

从执行结果图可以理解到Bean的生命周期是:

1.通过构造器创建实例

2.设置值

3.调用初始方法

4.使用Bean

5.销毁Bean

如果想在初始化之前或之后处理一些业务,比方说检查等操作,这时就可以用到BeanPostProcessor接口,写一个类实现BeanPostProcessor接口,实现对应的Before和After方法,然后在配置文件中配置后,Spring就会自动搜到这个类并为所有的Bean加上前置和后置处理。

示例代码如下:

package bean.cycle;
 
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
 
public class MyBeanPostProcessor implements BeanPostProcessor {
 
@Override
public Object postProcessAfterInitialization(Object bean, String arg1)
throws BeansException {
System.out.println("postProcessAfterInitialization...");
return bean;
}
 
@Override
public Object postProcessBeforeInitialization(Object bean, String arg1)
throws BeansException {
System.out.println("postProcessBeforeInitialization...");
return bean;
}
 
}

<bean class="bean.cycle.MyBeanPostProcessor"/>

执行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值