Bean的初始化有三种方法:
- 通过<bean> 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法
- 如果在上下文中定义的很多Bean都拥有相同名字的初始化方法和销毁方法,使用<beans>元素的default-init-method/default-destroy-method
- 通过实现InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法
package com.java.spring;
public class InitAndDestroy {
public void init() {
System.out.println("bean was born");
}
public void destroy() {
System.out.println("bean was dead");
}
public void coming() {
System.out.println("|I am coming");
}
}
package com.java.spring;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class InitDestroy implements InitializingBean, DisposableBean {
public void afterPropertiesSet() throws Exception {
System.out.println("InitDestroy was born");
}
public void destroy() throws Exception {
System.out.println("InitDestroy was dead");
}
public void coming() {
System.out.println("I am coming");
}
}
测试类:
package com.java.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Practice {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
InitDestroy id = (InitDestroy) ctx.getBean("InitDestroy");
id.coming();
((ClassPathXmlApplicationContext) ctx).close();//关闭应用上下文容器
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"
default-init-method="init"
default-destroy-method="destroy"
>
<!--
<bean id="initAnddestroy" class="com.java.spring.InitAndDestroy" />
-->
<!--
<bean id="initAnddestroy" class="com.java.spring.InitAndDestroy"
init-method="init" destroy-method="destroy"/>
-->
<bean id="InitDestroy" class="com.java.spring.InitDestroy" />
</beans>