Spring之生命週期
阿新 • • 發佈:2019-04-07
開始
啥不說,直接開始。
寫了個示例來演示Spring揭祕一文當中的Bean生命週期。
上圖
上程式碼
/** * 演示bean的生命週期 * Spring揭祕一文中寫道的週期:例項化bean物件 --> 設定物件屬性 --> 檢測Aware介面 * --> BeanPostProcessor前置邏輯 --> InitializingBean邏輯 --> init-method邏輯 * --> BeanPostProcessor後置邏輯 --> 使用中 --> DisposableBean邏輯 --> destroy-method邏輯 * * @Author guchenbo * @Date 2019/4/7. */ public class BeanLifeCycleTest implements ApplicationContextAware, InitializingBean, DisposableBean { private String name; public BeanLifeCycleTest() { System.out.println("例項化bean物件"); } public void setName(String name) { this.name = name; System.out.println("設定物件屬性"); } public void doing() { System.out.println("使用中"); } public void initMethod() { System.out.println("init-method邏輯"); } public void destroyMethod() { System.out.println("destroy-method邏輯"); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("檢測Aware介面"); } @Override public void destroy() throws Exception { System.out.println("DisposableBean邏輯"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("InitializingBean邏輯"); } public static class BeanFactoryProcessorTest implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("BeanPostProcessor前置邏輯"); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("BeanPostProcessor後置邏輯"); return bean; } } public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("lifecycle.xml"); BeanLifeCycleTest lifeCycleTest = (BeanLifeCycleTest) context.getBean("lifeCycleTest"); lifeCycleTest.doing(); context.destroy(); } }
上結果
BeanLifeCycleTest : 例項化bean物件
BeanLifeCycleTest : 設定物件屬性
BeanLifeCycleTest : 檢測Aware介面
BeanLifeCycleTest : BeanPostProcessor前置邏輯
BeanLifeCycleTest : InitializingBean邏輯
BeanLifeCycleTest : init-method邏輯
BeanLifeCycleTest : BeanPostProcessor後置邏輯
BeanLifeCycleTest : 使用中
BeanLifeCycleTest : DisposableBean邏輯
BeanLifeCycleTest : destroy-method邏輯