java-如何在TaskExecutionAutoConfiguration旁边创建其他TaskExecutor?
作者:互联网
我希望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.
根据docs,如果我们使bean成为自动配置的候选对象(这需要在META-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);
}
}
然后创建META-INF / spring.factories,其中包含:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
foo.bar.baz.qux.Config
标签:spring-boot,spring,java 来源: https://codeday.me/bug/20191211/2106996.html