Bean的生命周期
Spring Bean 的生命周期在整个 Spring 中占有很重要的位置,掌握这些可以加深对 Spring 的理解。
首先看下生命周期图:
再谈生命周期之前有一点需要先明确:
Spring 只帮我们管理单例模式 Bean 的完整生命周期,对于 prototype 的 bean ,Spring 在创建好交给使用者之后则不会再管理后续的生命周期。
@Bean指定初始化和销毁方法
实体类:
package com.wang.bean; public class Car { public Car(){ System.out.println("car cons..."); } public void init(){ System.out.println("car init..."); } public void destroy(){ System.out.println("car destroy..."); } }
xml方式:
<bean id="car" class="com.wang.bean.Car" scope="prototype" lazy-init="true" init-method="init" destroy-method="destroy"> </bean>
注解方式:
/** * Bean的生命周期 * ---由容器管理bean的创建,初始化,销毁 * * 构造,创建对象 * 单实例:在容器启动的时候创建对象 * 多实例:在每次获取的时候创建对象 * * 初始化: * 对象创建完成,并赋值好,调用初始化方法... * 销毁: * 单实例:容器关闭时,进行销毁 * 多实例:容器不会管理这个bean,bean不会销毁 * 1).使用自定义的初始化和销毁方法 * 指定init-methdo和destroy-method * * * */ @Configuration public class LifeCycleConfig { //@Scope("prototype") @Bean(initMethod = "init",destroyMethod = "destroy") public Car car(){ return new Car(); } }
Test:
@Test public void test(){ AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(LifeCycleConfig.class); System.out.println("容器创建完成"); annotationConfigApplicationContext.getBean("car");//多实例,获取bean时调用创建对象,容器关闭不会销毁bean annotationConfigApplicationContext.close();//关闭容器,执行销毁方法 }
InitializingBean和DisposableBean.