简体   繁体   English

在运行线程中自动装配或注入Bean

[英]Autowire or Inject Bean in Running thread

I'm running a Spring Boot app, I have configured in my App config class: 我正在运行一个Spring Boot应用程序,已经在我的App config类中进行了配置:

    @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: 我用TaskExecutor通过以下方式创建线程:

@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. 生产者和消费者,这两个类都实现了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. 我的线程按预期工作,但是当我尝试将Bean注入或自动装配到Consumer或Producer中时,它为空。

@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. 它们之所以为空,是因为您使用Spring的new ,辛辛苦苦构造了它们自己构造了它们。 If you construct an object yourself, Spring is unaware of it, and thus can't autowire anything. 如果您自己构造对象,Spring不会意识到它,因此无法自动装配任何东西。 The constructed objects are just regular objects, and not Spring beans. 构造的对象只是常规对象,而不是Spring bean。

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. 将共享队列定义为Spring Bean,将共享队列注入使用者和生产者中,并将消费者和生产者注入ProducerConsumer中。

Or inject SomeController into ProducerConsumer, and pass it as argument to the constructor of the Consumer and of the Producer. 或将SomeController注入ProducerConsumer中,并将其作为参数传递给Consumer和Producer的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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