spring 容器对象的生命周期:
1、spring 容器创建对象
2、执行 init-method 方法
3、调用自己的方法
4、关闭 spring 容器时,执行 destroy-method 方法。
2、applicationContext-initdestroy.xml 中添加属性 init-method 和 destroy-method
结果:new instance
init
hello
destroy
1、spring 容器创建对象
2、执行 init-method 方法
3、调用自己的方法
4、关闭 spring 容器时,执行 destroy-method 方法。
示例代码:
1、建 HelloWorld.java
public class HelloWorld {
public HelloWorld(){
System.out.println("new instance ------");
}
public void init(){ // 方法名任意
s.o.p("init")
}
public void destroy(){ // 方法名任意
s.o.p("destroy")
}
public void hello(){
System.out.println("hello");
}
}
2、applicationContext-initdestroy.xml 中添加属性 init-method 和 destroy-method
<bean id="helloInitDestroy" class="cn.google.spring.initdestroy.HelloWorld"
init-method="init" destroy-method="destroy"></bean>
3、测试方法:
public class InitDestroyTest{
@Test
public void testInitDestroy(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloInitDestroy");
helloWorld.hello();
ClassPathXmlApplicationContext app = (ClassPathXmlApplicationContext)context;
app.close();
}
}
结果:new instance
init
hello
destroy