spring – registerShutdownHook()和close()之间有什么区别

 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退出之前关闭,这几乎就是调用方法的时候,因为它是最后一行代码

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...