简体   繁体   中英

Autowire or Inject Bean in Running thread

I'm running a Spring Boot app, I have configured in my App config class:

    @Bean
public ThreadPoolTaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
    pool.setCorePoolSize(5);
    pool.setMaxPoolSize(10);
    pool.setWaitForTasksToCompleteOnShutdown(true);
    return pool;
}

I create my thread with TaskExecutor this way:

@Configuration
public class ProducerConsumer {
@Inject
TaskExecutor taskExecutor;


    Producer producer = new Producer(sharedQueue);
    Consumer consumer = new Consumer(sharedQueue);

    taskExecutor.execute(producer);
    taskExecutor.execute(consumer);

Producer and Consumer, both classes implements Runnable. I got my threads working as expected, but when I try to Inject or Autowire a Bean into Consumer or Producer, it comes null.

@Component
public class Consumer implements Runnable {

@Autowired
SomeController someController;

public Consumer (BlockingQueue<String> sharedQueue) {
    this.sharedQueue = sharedQueue;
}

@Override
public void run() {
    while (true) {
        synchronized (sharedQueue) {
            //someController is null
            someController.someMethod();

How can I expose my thread to the application context so I can inject any others dependencies into my thread??

They come as null because you construct them yourself, using new , sinctead of lettinng Spring construct them. If you construct an object yourself, Spring is unaware of it, and thus can't autowire anything. The constructed objects are just regular objects, and not Spring beans.

Define the shared queue as a Spring bean, inject the shared queue in the consumer and the producer, and inject the consumer and the producer in ProducerConsumer.

Or inject SomeController into ProducerConsumer, and pass it as argument to the constructor of the Consumer and of the Producer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM