The ThreadPoolExecutorFactoryBean is a FactoryBean implementing DisposableBean. When being used in Spring's XML bean definition like this
<bean id="executorService"
class="org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean"/>
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?
I found this approach the most elegant:
@Configuration
public class Cfg {
public ExecutorService executorService() {
return executorServiceFactoryBean().getObject();
}
@Bean
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With