<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!--
init-method:对象的初始化方法
destroy-method:对象的销毁方法
-->
<bean id="helloWorld" init-method="init" destroy-method="destroy" class="cn.itcast.spring01.initdestory.HelloWorld"></bean>
</beans>
HelloWorld.java
package cn.itcast.spring01.initdestory;
public class HelloWorld {
public void say(){
System.out.println("HelloWorld");
}
public void init(){
System.out.println("init");
}
public void destroy(){
System.out.println("destroy");
}
public HelloWorld(){
System.out.println("new Helloworld");
}
}
InitDestroyTest.java
package cn.itcast.spring01.initdestory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class InitDestroyTest {
/**
* 在spring的配置文件中
* init-method="init"
* 说明在创建完对象后,立刻执行init方法,用来进行初始化
* destroy-method="destroy"
* * 当该bean为单例模式,才能调用该方法
* destroy方法在容器销毁的时候被调用
* * 当该bean为多例时,spring容器不负责容器的销毁工作
* * 如果该bean为多例时,当不用该bean时应该手动的销毁
*/
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("cn/itcast/spring01/initdestory/applicationContext.xml");
HelloWorld helloworld = (HelloWorld)context.getBean("helloWorld");
helloworld.say();
helloworld.destroy();
}
}
init和destroy方法
init在构造器执行完毕之后执行
destroy方法在spring关闭的时候执行