标签:
ApplicationContext.xml
<?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" class="com.spring.initdestroy.HelloWord"
init-method="init" destroy-method="destroy"></bean>
</beans>
测试类
package com.spring.initdestroy;
public class HelloWord {
public HelloWord(){
System.out.println("create Object");
}
public void hello(){
System.out.println("hello word!");
}
public void init(){
System.out.println("init");
}
public void destroy(){
System.out.println("destory");
}
}
测试方法
package com.spring.initdestroy.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.initdestroy.HelloWord;
public class HelloWordTest {
/**
*
* 在构造函数之后,立刻执行init方法
* 如果Spring容器没有执行close方法,则不执行销毁方法
* 如果Spring容器执行了close方法,在执行该方法之前要执行销毁方法
*
*/
@Test
public void testinitdestory(){
//启动Spring容器
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
//根据id把Spring容器中的bean提取出来
HelloWord helloWord = (HelloWord) context.getBean("helloWorld");
helloWord.hello();
ClassPathXmlApplicationContext applicationContext=(ClassPathXmlApplicationContext) context;
applicationContext.close();//Spring容器关闭
}
}
输出结果:
create Object
十一月 01, 2015 8:19:43 下午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@33b93f89: display name [org.springframework.context.support.ClassPathXmlApplicationContext@33b93f89]; startup date [Sun Nov 01 20:19:43 CST 2015]; root of context hierarchy
十一月 01, 2015 8:19:43 下午 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@e1bbc2f: defining beans [helloWorld]; root of factory hierarchy
init
hello word!
destory
执行流程
标签:
原文地址:http://www.cnblogs.com/thinkpad/p/4928588.html