我想春天加载默认ThreadPoolTaskExecutor的TaskExecutionAutoConfiguration。尽管我想为一些明确的副任务提供可能的其他执行程序:
ThreadPoolTaskExecutor
TaskExecutionAutoConfiguration
@Bean public ThreadPoolExecutor myRequestPool() { return (ThreadPoolExecutor) Executors.newFixedThreadPool(10); }
问题:在上面添加Bean,TaskExecutionAutoConfiguration将不再执行,并且不会初始化spring- default执行器,因为@ConditionalOnMissingBean(Executor.class)不再匹配:
@ConditionalOnMissingBean(Executor.class)
package org.springframework.boot.autoconfigure.task; public class TaskExecutionAutoConfiguration { @Lazy @Bean(name = APPLICATION_TASK_EXECUTOR_BEAN_NAME) @ConditionalOnMissingBean(Executor.class) public ThreadPoolTaskExecutor applicationTaskExecutor(TaskExecutorBuilder builder) { return builder.build(); }
问题:我如何仍让Spring创建两个bean?
TaskExecutionAutoConfiguration仅@ConditionalOnMissingBean(Executor.class)当处理该自动配置时(由于)不存在其他执行器bean时,才会创建执行器bean 。因此,为了同时创建我们的执行程序和中定义的执行程序TaskExecutionAutoConfiguration,我们需要确保我们的bean在执行之后TaskExecutionAutoConfiguration
根据docs,如果我们使bean成为自动配置的候选对象(需要在中添加@Configuration类META- INF/spring.factories),则可以使用@AutoConfigureAfter它来配置它,使其在TaskExecutionAutoConfiguration以下情况下进行处理:
@Configuration
META- INF/spring.factories
@AutoConfigureAfter
package foo.bar.baz.qux; @Configuration @AutoConfigureAfter(TaskExecutionAutoConfiguration.class) public class Config { @Bean public ThreadPoolExecutor myRequestPool() { return (ThreadPoolExecutor) Executors.newFixedThreadPool(10); } }
然后创建META-INF/spring.factories包含:
META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ foo.bar.baz.qux.Config