两种方式:
有一个豆子工具ApplicationListener
。 onApplicationEvent()将在上下文和所有bean被销毁之前被调用。 有一个bean实现Lifecycle或SmartLifecycle。 stop()将在上下文和所有bean被销毁之前被调用。
无论哪种方式,你都可以在Bean销毁机制发生之前关闭任务。
例如:
@Componentpublic class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> { @Autowired ThreadPoolTaskExecutor executor; @Autowired ThreadPoolTaskScheduler scheduler; @Override public void onApplicationEvent(ContextClosedEvent event) { scheduler.shutdown(); executor.shutdown(); } }


