一、实现 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属性指定的方法执行了