简体   繁体   English

@Async将bean范围从一个线程复制到另一个线程

[英]@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.

相关问题 Java:将属性从Bean复制到另一个 - Java: Copy properties from bean to an another one 将 POJO 内容从一个 bean 复制到另一个 bean - Copy POJO content from one bean to another 将属性从一个Bean复制到另一个实现构建器模式的Bean - Copy properties from one bean to another Bean implementing builder pattern 如何将属性从一个Java bean复制到另一个? - How to copy properties from one Java bean to another? 从一页导航到另一页(View Scope)时,在支持bean中设置属性不起作用 - Setting property in backing bean while navigating from one page to another (View Scope) doesn't work 如何将属性从一个 Bean 复制到另一个并忽略嵌套对象的属性 - How to copy properties from one Bean to Another and ignore nested Object's property 在异步任务中使用Spring Data Session bean。 作用域“会话”对于当前线程无效 - Using Spring Data Session bean in async task. Scope 'session' is not active for the current thread jsf将一个bean的字符串传递给另一个bean的字符串 - jsf passing a string made from one bean to a string in another bean 如何从另一个@Stateless bean调用一个@Stateless bean上的方法 - How to invoke method on one @Stateless bean from another @Stateless bean 将属性从一个bean复制到另一个bean:Java - Copying Properties from one bean into another: Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM