Spring之生命周期
< 返回列表时间: 2019-04-07来源:OSCHINA
【围观】麒麟芯片遭打压成绝版,华为亿元投入又砸向了哪里?>>>
开始
啥不说,直接开始。
写了个示例来演示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逻辑
热门排行