从bean强制关闭Spring的最佳方法是什么?

xcu*_*cut 7 java spring

我的应用程序使用Spring DefaultMessageListenerContainer来处理传入的消息.应用程序的主要方法已经注册了一个关闭钩子.

问题是:强制应用程序上下文关闭的最佳方法是什么?

如果我RuntimeException在消息监听器中抛出一个,它由容器处理,而不是传递.调用System.exit是否可以接受?我是否会将其传递ApplicationContext给需要关闭的每个班级,以便我可以打电话close()给它?

Boz*_*zho 13

您可以将应用程序上下文转换为ConfigurableApplicationContext并调用close()它.至少这是在Web应用程序环境中关闭上下文时发生的情况,如果servlet上下文被销毁的话.

如果你想获得ApplicationContext,你的bean可能会实现ApplicationContextAware

另一种选择是注入(或使用autowire @Autowired)应用程序上下文:

@Inject
private ApplicationContext ctx;
Run Code Online (Sandbox Code Playgroud)