我希望spring从TaskExecutionAutoConfiguration加载默认的ThreadPoolTaskExecutor.尽管我想为一些明确的副任务提供可能的其他执行程序:
@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?
最佳答案
仅当在处理自动配置时不存在其他执行器bean(由于@ConditionalOnMissingBean(Executor.class))时,才会创建TaskExecutionAutoConfiguration中的执行器bean.因此,为了创建我们的执行程序和TaskExecutionAutoConfiguration中定义的执行程序,我们需要确保在TaskExecutionAutoConfiguration之后处理了我们的bean.
原文链接:https://www.f2er.com/spring/531600.html根据docs,如果我们使bean成为自动配置的候选对象(这需要在@R_404_338@-INF / spring.factories中添加@Configuration类),则可以使用@AutoConfigureAfter将其配置为在TaskExecutionAutoConfiguration之后进行处理:
package foo.bar.baz.qux;
@Configuration
@AutoConfigureAfter(TaskExecutionAutoConfiguration.class)
public class Config {
@Bean
public ThreadPoolExecutor myRequestPool() {
return (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
}
}
然后创建@R_404_338@-INF / spring.factories,其中包含:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
foo.bar.baz.qux.Config