(本文为自己书写,如有
错误,请指正,大家共同进步,谢谢。)
Bean的销毁:
1.destroy-method属性;
<java 代码>
package com.deciphering;
import org.springframework.context.support.Abstract
ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public
class SimpleBean {
private static final String DEFAULT_NAME = "Mark";
private static final String DE_AGE = "20";
//添加setter getter方法
private String age = "0";
private String name;
public String getAge() {
return age;
}
public void setAge(String age) {
System.out.println("spring依赖注入。。");
this.age = age;
System.out.println("age" + this.age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SimpleBean(){
System.out.println("spring实例化bean。。。。");
}
//清理资源并回收
public void close(){
System.out.println("调用close()...");
}
public String toString(){
return name +"name\n" + age +"age\n";
}
//运行测试main的方法
public static void main(String[]args){
AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
context.getBean("simpleBean");//获取simpleBean实例
context.registerShutdownHook();//为spring注册关闭钩子
System.out.println("关闭。。。");
}
}
<.xml配置(局部)>
<bean name="simpleBean" class="com.deciphering.SimpleBean" destroy-method="close">
<property name="name" value="Bill"></property>
<property name="age" value="20"></property>
</bean>
<运行结果>
/*spring实例化bean。。。。
*spring依赖注入。。
*age20
*关闭。。。
*调用close()...
*/
2.DisposableBean
接口;
package com.deciphering;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SimpleBean implements DisposableBean{
private static final String DEFAULT_NAME = "Mark";
private static final String DE_AGE = "20";
//添加setter getter方法
private String age = "0";
private String name;
public String getAge() {
return age;
}
public void setAge(String age) {
System.out.println("spring依赖注入。。");
this.age = age;
System.out.println("age" + this.age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SimpleBean(){
System.out.println("spring实例化bean。。。。");
}
public String toString(){
return name +"name\n" + age +"age\n";
}
//运行测试main的方法
public static void main(String[]args){
AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
context.getBean("simpleBean");//获取simpleBean实例
context.registerShutdownHook();//为spring注册关闭钩子
System.out.println("关闭。。。");
}
public void destroy() throws Exception{
System.out.println("代用close()。。。。");
}
}
<.xml(局部)>
<bean name="simpleBean" class="com.deciphering.SimpleBean" >
<property name="name" value="Bill"></property>
<property name="age" value="20"></property>
</bean>
<运行结果>
/*
* spring实例化bean。。。。
spring依赖注入。。
age20
关闭。。。
代用close()。。。。
*/