Spring和Java EE中的@PersistenceContext EntityManager线程安全 [英] @PersistenceContext EntityManager thread-safety in Spring and Java EE

查看:241
本文介绍了Spring和Java EE中的@PersistenceContext EntityManager线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据定义,

EntityManager不是线程安全的. Servlet规范指出,在非分布式环境中且未实现SingleThreadModel,每个定义只有个servlet实例.

因此,在Java EE中,当您通过@PersistenceContextEntityManager注入到Servlet的字段中时-这不是线程安全的:

public class MyServlet extends HttpServlet {

    // Not thread-safe, should be using EMF instead.
    @PersistenceContext
    private EntityManager em;
}

  1. 这是正确的说法吗,即使Spring bean的默认范围是单例,但EntityManager是线程安全的,因为Spring使用ThreadLocal绑定其事务和EntityManager到它?/p>

  2. 上面的Servlets示例在Spring中仍然有效吗?它仍然不是线程安全的吗?

  3. ThreadLocal方法仅适用于Spring托管的bean,而普通的servlet不是其中之一吗?

  4. 据我所知,注入EntityManager是容器的责任.在Glassfish Java EE实现中,是应用服务器发现@PersistenceContext作为注入点.
    春天的样子如何? Spring框架负责发现这些注释吗,还是JPA实现者的责任?

解决方案

问题2、3和4 – Spring不会注意不是Spring Bean的任何类.因此,Spring不会关注您的MyServlet类. 因此,答案是

  • 2)是
  • 3)仅Spring托管Beans
  • 4)这是Springs的责任,因为Spring是容器

对于问题1).它以这种方式工作,因此使用Spring Injected Entity Manager可以有效地节省线程.

EntityManager is not thread-safe by definition. Servlets specs says that in non-distributed environment and without implementing SingleThreadModel, there is only one servlet instance per definition.

Therefore, in Java EE when you inject an EntityManager through the @PersistenceContext into Servlet's field - it's not thread safe:

public class MyServlet extends HttpServlet {

    // Not thread-safe, should be using EMF instead.
    @PersistenceContext
    private EntityManager em;
}

  1. Is this correct to say that even though the default scope of Spring beans is singleton, the EntityManager is thread-safe as the Spring uses ThreadLocal to bind its transaction and EntityManager to it?

  2. Is the above Servlets example still valid in Spring? Is it still not thread-safe?

  3. Does the ThreadLocal approach works only for Spring managed beans and plain servlet is not one of those?

  4. As far as I remember, it's the container responsibility to inject the EntityManager. In Glassfish Java EE implementation, it was the application server who discovers the @PersistenceContext as injection point.
    How does it look like in Spring? Is the Spring Framework responsible for discovering those annotations or it's responsibility of the JPA implementor?

解决方案

Question 2, 3, and 4 -- Spring does not pay attention to any class that is not a Spring Bean. Therefor Spring does not pay attention to you MyServlet class. Therefore the answer for

  • 2) is no
  • 3) only Spring managed Beans
  • 4) it is Springs responsibility, because Spring is the Container

For Question 1). It works this way, so the usage of an Spring Injected Entity Manager is effective thread save.

这篇关于Spring和Java EE中的@PersistenceContext EntityManager线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆