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

use*_*067 5 spring

 HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
  obj.getMessage();
  context.registerShutdownHook();  
Run Code Online (Sandbox Code Playgroud)

输出下方:

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.  
Run Code Online (Sandbox Code Playgroud)

而使用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.
Run Code Online (Sandbox Code Playgroud)

有人可以解释这个区别吗?

nic*_*ild 12

ApplicationContext类不定义了上述两种方法作为其接口的一部分,但ConfigurableApplicationContext确实定义了这两个.

来自JavaDoc:

  • close() - 关闭此应用程序上下文,销毁其bean工厂中的所有bean.
  • registerShutdownHook() - 向JVM运行时注册一个关闭钩子,在JVM关闭时关闭此上下文,除非此时它已经关闭.

基本上,AbstractApplicationContext#close()它将ApplicationContext在调用时AbstractApplicationContext#registerShutdownHook()关闭或关闭,同时将关闭或关闭ApplicationContextJVM在以后出于某种原因关闭的时间.这将通过利用JVM关闭挂钩功能来实现.

在任何一种情况下,实际的关闭都是通过该doClose()方法完成的.

如果你很好奇为什么你的输出看起来如此相似,那是因为无论你是打电话#close()还是#registerShutdownHook()在你的第3行,他们都在做同样的事情. #close将立即关闭,并将#registerShutdownHook在JVM退出之前关闭,这几乎是在调用方法时,因为它是最后一行代码!

  • 关于从官方文档中调用“registerShutdownHook()”的五美分 - _这样做可以确保正常关闭并在单例 bean 上调用相关的销毁方法,以便释放所有资源。当然,您仍然必须正确配置和实现这些销毁回调_ [来源](https://docs.spring.io/spring/docs/5.0.3.RELEASE/spring-framework-reference/core.html#beans-factory -关闭) (3认同)