无法通过spring.boot.autoconfigure.task自动连接ThreadPoolTask​​Executor

时间:2019-09-12 06:16:50

标签: spring spring-boot

我尝试使用spring的ThreadPoolTask​​Executor。我发现在org.springframework.boot.autoconfigure.task中创建了bean,但是无法将其自动连接到我的组件。

public class TaskExecutionAutoConfiguration {

...

@Lazy
@Bean(
            name = {"applicationTaskExecutor", "taskExecutor"}
        )
@ConditionalOnMissingBean({Executor.class})
    public ThreadPoolTaskExecutor applicationTaskExecutor(TaskExecutorBuilder builder) {
            return builder.build();
    }
}

然后我尝试通过Qualifier自动接线

@Autowired
@Qualifier("applicationTaskExecutor")
public void setThreadPoolTaskExecutor(ThreadPoolTaskExecutor threadPoolTaskExecutor) {
        this.threadPoolTaskExecutor = threadPoolTaskExecutor;
}

但是我在IDE中说他找不到这个bean。 我不明白什么?

2 个答案:

答案 0 :(得分:2)

您可以使用@AutoWired注解注入ThreadPoolExecutor。然后使用@PostConstruct批注设置属性。示例代码如下。

package com.example.workers;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

@Service
   public class EmailComponent {
    private class MessagePrinterTask implements Runnable {

        private String message;

        public MessagePrinterTask(String message) {
            this.message = message;
        }

        public void run() {
            System.out.println(message);
        }

    }

    @Autowired
    ThreadPoolTaskExecutor executor;

    @PostConstruct
    public void init() {
        executor.setCorePoolSize(5); //or read from properties file
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(25);
    }

    public EmailComponent() {

    }
    public void startJob() {
        for(int i = 0; i < 25; i++) {
            executor.execute(new MessagePrinterTask("Message" + i));
        }
    } 






 }

答案 1 :(得分:0)

使用时需要添加@Lazy注解。

@Lazy
@Autowired
@Qualifier("applicationTaskExecutor")
public void setThreadPoolTaskExecutor(ThreadPoolTaskExecutor threadPoolTaskExecutor) {
        this.threadPoolTaskExecutor = threadPoolTaskExecutor;
}