Spring_管理bean的生命周期
2021-01-08 04:32
标签:except 构造 actor factor 工厂 调用 eth config car Spring IOC 容器对 Bean 的生命周期进行管理的过程: beans-cycle.xml MyBeanPostProcessor.java Main Car Spring_管理bean的生命周期 标签:except 构造 actor factor 工厂 调用 eth config car 原文地址:https://www.cnblogs.com/afangfang/p/12967770.html
通过构造器或工厂方法创建 Bean 实例
为 Bean 的属性设置值和对其他 Bean 的引用
将 Bean 实例传递给 Bean 后置处理器的 postProcessBeforeInitialization 方法
调用 Bean 的初始化方法
将 Bean 实例传递给 Bean 后置处理器的 postProcessAfterInitialization方法
Bean 可以使用了
当容器关闭时, 调用 Bean 的销毁方法xml version="1.0" encoding="UTF-8"?>
beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
bean id="car" class="com.aff.spring.beans.cycle.Car" init-method="init2" destroy-method="detory">
property name="brand" value="Audi" />
bean>
bean class="com.aff.spring.beans.cycle.MyBeanPostProcessor">bean>
beans>
package com.aff.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 {
System.out.println("postProcessBeforeInitialization:"+bean+","+beanName);
if ("car".equals(beanName)) {
//...
}
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;
}
}
package com.aff.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(car);
// 关闭IOC容器
ctx.close();
}
}
package com.aff.spring.beans.cycle;
public class Car {
public Car() {
System.out.println("Car‘s Construct...");
}
private String brand;
public void setBrand(String brand) {
System.out.println("set Brand...");
this.brand = brand;
}
public void init2() {
System.out.println("init...");
}
public void detory() {
System.out.println("destory ...");
}
@Override
public String toString() {
return "Car [brand=" + brand + "]";
}
}
文章标题:Spring_管理bean的生命周期
文章链接:http://soscw.com/index.php/essay/40863.html