1
我運行一個Spring應用程序啓動,我已經配置在我的應用程序配置類:自動裝配或注入豆在正在運行的線程
@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();
我怎樣才能暴露我的線程應用程序上下文,所以我可以注入任何依賴別人進入我的線?