Spring ThreadPoolTask​​Executor自动装配不同的实例

时间:2018-02-19 09:14:44

标签: spring dependency-injection threadpoolexecutor

我正在使用Spring Boot,并按如下方式配置了ThreadPoolTaskExecutor

 @Data
    @Configuration
    public class WorkflowThreadConfig {

        @Value("${threadConfig.corePoolSize}")
        private Integer corePoolSize;

        @Value("${threadConfig.maxPoolSize}")
        private Integer maxPoolSize;

            @Bean
            @Qualifier("threadPoolTaskExecutor")
            public TaskExecutor threadPoolTaskExecutor() {       
                ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();       
                threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
                threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
                log.debug("threadPoolTaskExecutor maxPoolSize  is : " + threadPoolTaskExecutor.getMaxPoolSize());
                threadPoolTaskExecutor.setThreadNamePrefix("workflow_thread_");
                threadPoolTaskExecutor.initialize();
                return threadPoolTaskExecutor;
            }
        }

@Autowire @Bean使用@Qualifier进入另一个类时,我看到最大池大小的默认线程数,而不是我提供的数字(10)即使在评论了我的大部分代码并使用@PostConstruct

之后,也可以进行配置
@Component
public class WorkflowTaskScheduler {

//@Autowired
    //private WorkflowThreadManager workflowThreadManager;

    @Autowired
    @Qualifier("threadPoolTaskExecutor")
    private TaskExecutor taskExecutor;

    @PostConstruct
    public void workflowTaskScheduler(){
        ThreadPoolTaskExecutor threadPool = (ThreadPoolTaskExecutor) taskExecutor;
         log.debug(" Max Thread Pool count is : " + threadPool.getMaxPoolSize());
    }

}

日志:

SpanId="">threadPoolTaskExecutor maxPoolSize  is : 10</L_MSG>
SpanId=""> Max Thread Pool count is : 2147483647</L_MSG>

另一个有趣的观点是,当我从@QualifierthreadPoolTaskExecutor @Bean移除@Autowired TaskExecutor注释时,我收到以下错误:

Field taskExecutor in com.package.WorkflowTaskScheduler required a single bean, but 2 were found:
    - threadPoolTaskExecutor: defined by method 'threadPoolTaskExecutor' in class path resource [com/package/WorkflowThreadConfig.class]
    - taskScheduler: defined in null

1 个答案:

答案 0 :(得分:0)

两种选择: 1.使用不同的限定符然后使用camelcase。 myThreadPoolTask​​Executor

  1. 在ThreadPoolTask​​Executor上使用@primary。所以它将是默认捆绑的那个