我需要在 Spring 中创建一个永远循环的线程,并在 LinkedBlockingQueue.take() 上阻塞以处理其中的对象(控制器将对象放入该队列中)。如果在@Controller 中处理我的代码,则可以正常工作。但是,现在我将它移到线程中,我从 Hibernate 获得了多个 LazyInitializationException。简而言之,我的线程的伪代码骨架是:
@Component
public class AsynchronousConsumer implements Runnable
{
@Autowire
// Service Layer and other goodies (all correctly injected)
@PostConstruct
public void init(){
(new Thread(this)).start();
}
// Note that an @Controller action is placing MyBean in the queue
protected static LinkedBlockingQueue<MyBean> queue = new LinkedBlockingQueue<MyBean>();
@Override
public void run()
{
while(true)
{
MyBean myBean = queue.take();
this.processBean(myBean); // do the processing
}
}
void processBean(MyBean m)
{
// Hybernate exceptions happen when retrieving objects from the DB
}
}
我在这里做错了吗?我应该如何启动我的线程以使其完全了解 Spring/Hibernate?