You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 19+SpringBoot中自定义ExecutorService Bean为何不调用shutdown方法?

SpringBoot测试无法结束:自定义ExecutorService未自动执行shutdown的问题及解决

问题现象

在Java 19环境下搭配SpringBoot 2.7.12或3.1.0版本时,自定义的ExecutorService Bean不会自动调用shutdown方法,导致@SpringBootTest测试始终无法正常结束。

触发场景

该问题仅在同时满足以下条件时出现:

  • 自定义了ExecutorService类型的Bean
  • 配置类实现了SchedulingConfigurer接口
  • 配置类中存在带有@Scheduled注解的方法

注:根据@Bean的JavaDoc说明,destroyMethod会被Spring自动推断,shutdown是默认的可选推断方法之一,但在此场景下自动推断机制失效。

触发问题的代码示例

调度配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }

    @Bean
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(10);
    }

    /**
     * 移除该@Scheduled注解后测试可正常结束
     */
    @Scheduled(cron = "0 0 1 * * *")
    protected void schedule() {

    }
}

测试类

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest(
        classes =
                {ScheduleConfig.class})
class TestIT {

    @Test
    void test() {
        // 空测试逻辑
    }
}

解决方法

显式为@Bean注解设置destroyMethod参数为"shutdown",强制Spring在容器销毁时调用该方法。修改后的Bean定义如下:

@Bean(destroyMethod = "shutdown")
public Executor taskExecutor() {
    return Executors.newScheduledThreadPool(10);
}

内容的提问来源于stack exchange,提问作者Suniram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 07:12:47