HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
context.registerShutdownHook();
输出下方:
Feb 03,2017 11:46:12 AM org.springframework.context.support.ClasspathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClasspathXmlApplicationContext@799f7e29: startup date [Fri Feb 03 11:46:12 IST 2017]; root of context hierarchy
Feb 03,2017 11:46:12 AM org.springframework.beans.factory.xml.XmlBeanDeFinitionReader loadBeanDeFinitions
INFO: Loading XML bean deFinitions from class path resource [Beans.xml]
Bean is going through init.
Your Message : Hello World!
Bean will destroy Now.
而使用context.close()给出
Feb 03,2017 11:53:57 AM org.springframework.context.support.ClasspathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClasspathXmlApplicationContext@799f7e29: startup date [Fri Feb 03 11:53:57 IST 2017]; root of context hierarchy
Feb 03,2017 11:53:57 AM org.springframework.beans.factory.xml.XmlBeanDeFinitionReader loadBeanDeFinitions
INFO: Loading XML bean deFinitions from class path resource [Beans.xml]
Bean is going through init.
Your Message : Hello World!
Feb 03,2017 11:53:57 AM org.springframework.context.support.ClasspathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClasspathXmlApplicationContext@799f7e29: startup date [Fri Feb 03 11:53:57 IST 2017]; root of context hierarchy
Bean will destroy Now.
有人可以解释这个区别吗?
最佳答案
ApplicationContext
类没有将这些方法中的任何一个定义为其接口的一部分,但ConfigurableApplicationContext
确实定义了这两个方法.
来自JavaDoc:
- 07002 — Close this application context,destroying all beans in its bean factory.
- 07003 — Register a shutdown hook with the JVM runtime,closing this context on JVM shutdown unless it has already been closed at that time.
基本上,AbstractApplicationContext #close()将在调用时关闭或关闭ApplicationContext,而AbstractApplicationContext #registerShutdownHook()将在JVM因任何原因关闭的时候关闭或关闭ApplicationContext.这将通过利用JVM关闭挂钩功能来实现.
在任何一种情况下,实际的关闭都是通过doClose()方法完成的.
如果您对输出看起来如此相似的原因感到好奇,那是因为它们实际上是在做同样的事情,无论您是在示例的第3行调用#close()还是#registerShutdownHook(). #close会立即关闭,而#registerShutdownHook将在JVM退出之前关闭,这几乎就是调用方法的时候,因为它是最后一行代码!