Multithreading 在运行线程中自动连接或注入Bean
我正在运行Spring Boot应用程序,我已在我的应用程序配置类中配置:Multithreading 在运行线程中自动连接或注入Bean,multithreading,spring,dependency-injection,spring-boot,autowired,Multithreading,Spring,Dependency Injection,Spring Boot,Autowired,我正在运行Spring Boot应用程序,我已在我的应用程序配置类中配置: @Bean public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor(); pool.setCorePoolSize(5); pool.setMaxPoolSize(10); pool.setWaitForTasksToComplet
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setCorePoolSize(5);
pool.setMaxPoolSize(10);
pool.setWaitForTasksToCompleteOnShutdown(true);
return pool;
}
我使用TaskExecutor以以下方式创建线程:
@Configuration
public class ProducerConsumer {
@Inject
TaskExecutor taskExecutor;
Producer producer = new Producer(sharedQueue);
Consumer consumer = new Consumer(sharedQueue);
taskExecutor.execute(producer);
taskExecutor.execute(consumer);
生产者和消费者,这两个类都实现Runnable。
我让线程按预期工作,但当我尝试将Bean注入或自动连接到消费者或生产者时,它将为空
@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();
@组件
公共类使用者实现可运行{
@自动连线
SomeController-SomeController;
公共消费者(阻止队列共享队列){
this.sharedQueue=sharedQueue;
}
@凌驾
公开募捐{
while(true){
已同步(共享队列){
//someController为空
someController.someMethod();
如何将我的线程暴露于应用程序上下文中,以便将任何其他依赖项注入到我的线程中?它们为空,因为您使用
new
,而不是让Spring构造它们。如果您自己构造对象,Spring不知道它,因此无法自动关联任何内容ucted对象只是常规对象,而不是springbean
将共享队列定义为Springbean,在使用者和生产者中注入共享队列,并在ProducerConsumer中注入使用者和生产者
或者将SomeController注入ProducerConsumer,并将其作为参数传递给使用者和生产者的构造函数