使用@PreDestroy关闭@Bean ExecutorService

zen*_*337 1 java spring javabeans executorservice predestroy

我有一个 Spring @Configuration 类,如下所示:

@Configuration
public class ExecutorServiceConfiguration {

    @Bean
    public BlockingQueue<Runnable> queue() {
        return ArrayBlockingQueue<>(1000);
    }     

    @Bean
    public ExecutorService executor(BlockingQueue<Runnable> queue) {
        return ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, queue);
    }

    @PreDestroy
    public void shutdownExecutor() {
        // no executor instance
    }
}
Run Code Online (Sandbox Code Playgroud)

我还想指定一种@PreDestroy关闭 ExecutorService 的方法。但是,该@PreDestroy方法不能有任何参数,这就是为什么我无法将executorbean 传递给该方法以关闭它的原因。指定 destroy 方法也@Bean(destroyMethod = "...")不起作用。它允许我指定现有的shutdownor shutdownNow,但不能指定我打算使用的自定义方法。

我知道我可以直接实例化队列和执行器,而不是作为 Spring bean,但我宁愿这样做。

gpe*_*che 5

我喜欢内联定义类:

@Bean(destroyMethod = "myCustomShutdown")
public ExecutorService executor(BlockingQueue<Runnable> queue) {
    return new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, queue) {
        public void myCustomShutdown() {
            ...
        }
    };
}
Run Code Online (Sandbox Code Playgroud)