Spring - IoC(10): 生命周期
Spring 容器可以管理 singleton 作用域 Bean 的生命周期,容器能够跟踪 Bean 实例的创建、销毁。管理 Bean 生命周期行为主要有两个时机:
注入 Bean 的依赖关系之后
即将销毁 Bean 之间
依赖关系注入之后的行为
有三种方式可以在 Bean 的所有属性设置成功后执行特定的行为:
实现 org.springframework.beans.factory.InitializingBean 接口
使用 init-method 属性
使用 @PostConstruct 注解
实现 InitializingBean 接口的示例
Bean 的定义:
public class ExampleBean implements InitializingBean { private String field1; private String field2; public void setField1(String field1) { this.field1 = field1; System.out.println("field1 was set."); } public void setField2(String field2) { this.field1 = field2; System.out.println("field2 was set."); } public ExampleBean() { System.out.println("In ExampleBean Constructor."); } public void afterPropertiesSet() throws Exception { System.out.println("All properties were set."); } }
Spring 配置:
<bean id="eb" class="com.huey.dream.bean.ExampleBean"> <property name="field1" value=""/> <property name="field2" value=""/> </bean>
测试方法:
@Test public void testLifecycle() throws Exception { ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml"); }
结果输出:
In ExampleBean Constructor.
field1 was set.
field2 was set.
All properties were set.
使用 init-method 属性的示例
Bean 的定义:
public class ExampleBean { private String field1; private String field2; public void setField1(String field1) { this.field1 = field1; System.out.println("field1 was set."); } public void setField2(String field2) { this.field1 = field2; System.out.println("field2 was set."); } public ExampleBean() { System.out.println("In ExampleBean Constructor."); } public void init() throws Exception { System.out.println("In init method."); } }
Spring 配置:
<bean id="eb" class="com.huey.dream.bean.ExampleBean" init-method="init"> <property name="field1" value=""/> <property name="field2" value=""/> </bean>
使用 @PostConstruct 注解
Bean 的定义:
public class ExampleBean { private String field1; private String field2; public void setField1(String field1) { this.field1 = field1; System.out.println("field1 was set."); } public void setField2(String field2) { this.field1 = field2; System.out.println("field2 was set."); } public ExampleBean() { System.out.println("In ExampleBean Constructor."); } @PostConstruct public void init() throws Exception { System.out.println("In init method."); } }
Spring 配置:
<bean id="eb" class="com.huey.dream.bean.ExampleBean"> <property name="field1" value=""/> <property name="field2" value=""/> </bean>
Bean 销毁之前的行为
与定制初始化行为类似,也有三种方式可以在 Bean 实例销毁前执行特定的行为:
实现 org.springframework.beans.factory.DisposableBean 接口
使用 destroy-method 属性
使用 @PreDestroy 注解