Spring在非web應用中關閉IoC容器 (registerShutdownHook)


  在基於web的ApplicationContext實現中,已有相應的實現來處理關閉web應用時恰當地關閉Spring IoC容器。但,如果你正在一個非web應用的環境下使用Spring的IoC容器,如dubbo服務,你想讓容器優雅的關閉,並調用singleton的bean相應destory回調方法,你需要在JVM里注冊一個“關閉鈎子”(shutdown hook)。這一點非常容易做到,並且將會確保你的Spring IoC容器被恰當關閉,以及所有由單例持有的資源都會被釋放。

      為了注冊“關閉鈎子”,你只需要簡單地調用在org.springframework.context.support.AbstractApplicationContext實現中的registerShutdownHook()方法即可。

 1 public final class StartServer {
 2  
 3     public static void main(final String[] args) throws Exception {
 4         AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(new String []{"spring.xml"});
 5  
 6         // add a shutdown hook for the above context... 
 7         ctx.registerShutdownHook();
 8         ctx.start();
 9         // app runs here...
10         // main method exits, hook is called prior to the app shutting down...
11     }
12 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM