Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Using FactoryBean and DisposableBean with Spring's Java Config

The ThreadPoolExecutorFactoryBean is a FactoryBean implementing DisposableBean. When being used in Spring's XML bean definition like this

<bean id="executorService" 

the created bean will be an instance of ExecutorService and ensures ThreadPoolExecutorFactoryBean#destroy() is called, once the Spring Application Context is shut down.

Is it possible to configure such a bean with a Spring 3's @Configuration class?

like image 264
Lars Avatar asked Feb 19 '23 19:02


1 Answers

I found this approach the most elegant:

public class Cfg {

    public ExecutorService executorService() {
        return executorServiceFactoryBean().getObject();

    public ThreadPoolExecutorFactoryBean executorServiceFactoryBean() {
        return new ThreadPoolExecutorFactoryBean();


Notice that executorService() is not annotated with @Bean - but you can still call it from other @Bean-methods requiring ExecutorService. Since ThreadPoolExecutorFactoryBean is annotated with @Bean, Spring will automatically manage its lifecycle (detect DisposableBean, etc.)

like image 111
Tomasz Nurkiewicz Avatar answered Feb 27 '23 14:02

Tomasz Nurkiewicz