Spring_管理bean的生命周期

2021-01-08 04:32

阅读:479

标签:except   构造   actor   factor   工厂   调用   eth   config   car   

 

Spring IOC 容器对 Bean 的生命周期进行管理的过程:
通过构造器或工厂方法创建 Bean 实例
为 Bean 的属性设置值和对其他 Bean 的引用
将 Bean 实例传递给 Bean 后置处理器的 postProcessBeforeInitialization 方法
调用 Bean 的初始化方法
将 Bean 实例传递给 Bean 后置处理器的 postProcessAfterInitialization方法
Bean 可以使用了
当容器关闭时, 调用 Bean 的销毁方法

beans-cycle.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" 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>

 

MyBeanPostProcessor.java

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;
    }
}

 

Main

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();
    }
}

 

 Car

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的生命周期

标签:except   构造   actor   factor   工厂   调用   eth   config   car   

原文地址:https://www.cnblogs.com/afangfang/p/12967770.html

上一篇:C语言简介

下一篇:Ajax


评论


亲,登录后才可以留言!