[英]@Async Copy bean scope from one thread to another
I´m using Spring @Async
to make async request, and I would like to know, how can I pass beans like the Hibernate session from one thread to other when I´m using @Async
? 我使用Spring @Async
发出异步请求,我想知道,当我使用@Async
时,如何将Hibernate会话之类的bean从一个线程传递到另一个线程?
Regards. 问候。
You can't pass the Hibernate session to another thread. 您不能将Hibernate会话传递给另一个线程。 Some beans are connected to the current thread. 一些bean连接到当前线程。 The active database transaction is one such bean. 活动数据库事务就是这样的一个bean。 Spring keeps that in a ThreadLocal
and there is no API to pass this to another thread. Spring将其保存在ThreadLocal
,没有API可以将其传递给另一个线程。
What you will have to do is pass the objects that you want to work on to the new thread, get a new session there and em.merge()
the objects into the new session. 您需要做的是将您要处理的对象传递到新线程,在那里获得一个新会话,并将对象em.merge()
进入新会话。 Or, if you want to be really clean, you can just pass the primary keys and load the objects again from Hibernate. 或者,如果您想真正干净,只需传递主键并从Hibernate重新加载对象即可。 Since they will probably be in the cache, this shouldn't be very expensive. 由于它们可能会在缓存中,所以它应该不会很昂贵。
Just provide the bean scope in ApplicationContext or with Annotation where the bean is declared. 只需在ApplicationContext中提供bean范围,或在声明bean的地方提供Annotation。 You don't have to do anything explicit to copy the scope if the bean is used by multiple threads 如果该bean被多个线程使用,则无需执行任何显式操作即可复制作用域
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.