简体   繁体   中英

@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 ?

Regards.

You can't pass the Hibernate session to another thread. Some beans are connected to the current thread. The active database transaction is one such bean. Spring keeps that in a ThreadLocal and there is no API to pass this to another thread.

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. Or, if you want to be really clean, you can just pass the primary keys and load the objects again from 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. You don't have to do anything explicit to copy the scope if the bean is used by multiple threads

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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