一尘不染

如何在TaskExecutionAutoConfiguration旁边创建其他TaskExecutor?

spring-boot

我想春天加载默认ThreadPoolTaskExecutorTaskExecutionAutoConfiguration。尽管我想为一些明确的副任务提供可能的其他执行程序:

@Bean
public ThreadPoolExecutor myRequestPool() {
    return (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
}

问题:在上面添加Bean,TaskExecutionAutoConfiguration将不再执行,并且不会初始化spring-
default执行器,因为@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?


阅读 583

收藏
2020-05-30

共1个答案

一尘不染

TaskExecutionAutoConfiguration@ConditionalOnMissingBean(Executor.class)当处理该自动配置时(由于)不存在其他执行器bean时,才会创建执行器bean
。因此,为了同时创建我们的执行程序和中定义的执行程序TaskExecutionAutoConfiguration,我们需要确保我们的bean在执行之后TaskExecutionAutoConfiguration

根据docs,如果我们使bean成为自动配置的候选对象(需要在中添加@ConfigurationMETA- INF/spring.factories),则可以使用@AutoConfigureAfter它来配置它,使其在TaskExecutionAutoConfiguration以下情况下进行处理:

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包含:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  foo.bar.baz.qux.Config
2020-05-30