Spring IoC容器-03-工廠級生命週期

一、實現 BeanFactoryPostProcessor spring

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

/**
 * 工廠級生命週期
 */
public class FactoryLifecycle implements BeanFactoryPostProcessor {

    /**
     * 構造器
     */
    public FactoryLifecycle () {
        System.out.println("一 【工廠級別】FactoryLifecycle構造器執行了");
    }

    /**
     * Bean實例化以前
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("二 【工廠級別】postProcessBeanFactory方法執行了");
    }
}

二、xml配置 spring-chapter2-containerlifecycle.xmlide

<?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">

    <!--BeanLifecycle-->
    <bean id="factoryLifecycle" 
      class="com.test.lifecycle.factorylifecycle.FactoryLifecycle">
    </bean>

</beans>

三、測試post

import com.test.lifecycle.beanlifcycle.BeanLifecycle;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Bean級生命週期 + 容器級生命週期 + 工廠級生命週期測試
 */
public class FactoryLifecycleTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "classpath:spring-chapter2-beanlifecycle.xml",
                "classpath:spring-chapter2-containerlifecycle.xml", 
                "classpath:spring-chapter2-factorybeanlifecycle.xml");
        BeanLifecycle beanLifecycle = context.getBean("beanLifecycle",BeanLifecycle.class);
        beanLifecycle.sayHello();
        context.close();
    }
}

四、運行結果測試

一 【工廠級別】FactoryLifecycle構造器執行了
二 【工廠級別】postProcessBeanFactory方法執行了
① 【容器級別】ContainerLifecycle構造器執行了
② 【容器級別】postProcessBeforeInstantiation方法執行了,class=class com.test.lifecycle.beanlifcycle.BeanLifecycle
1. 【Bean級別】構造器執行了
③ 【容器級別】postProcessPropertyValues方法執行了,beanName=class com.test.lifecycle.beanlifcycle.BeanLifecycle
2. 【Bean級別】setBeanName方法執行了
3. 【Bean級別】setApplicationContext方法執行了
4. 【Bean級別】afterPropertiesSet方法執行了
5. 【Bean級別】init-method指定的方法執行了
④ 【容器級別】postProcessAfterInitialization方法執行了,beanName=class com.test.lifecycle.beanlifcycle.BeanLifecycle
6. 【Bean級別】sayHello方法執行了
7. 【Bean級別】destroy方法執行了
8. 【Bean級別】destroy-method屬性指定的方法執行了
相關文章
相關標籤/搜索