将EJB作为实例变量注入到servlet中是否安全? [英] Is it safe to inject an EJB into a servlet as an instance variable?

查看:67
本文介绍了将EJB作为实例变量注入到servlet中是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道,在Web层中,可能仅存在一个给定Servlet的单个实例来服务多个请求。这可能导致实例变量中出现线程问题。



我的问题是,使用@EJB注释将EJB作为实例变量注入EJB是否安全? / p>

在相同的EJB实例将同时服务多个请求的假设下,我的最初直觉不会。似乎这也将是许多其他程序员的本能:不要注入servlet



但是我跳了一个错误的结论。显然,注入到servlet中的是代理,在实际情况下,容器是否实际上以不同的实例服务每个请求并维护线程安全?正如该论坛建议的那样:不要注入servlet



似乎有很多矛盾的意见。

解决方案

您的参考文献不要注入servlet中没有提及ejbs或@ejb注释。



根据EJB规范,您可以从包括servlet在内的各种远程客户端访问ejb(EJB 3.0规范(JSR-220)-第3.1节)。使用@EJB注释注入ejb是一种通过依赖项注入(第3.4.1节)获得EJB接口的方法,它是在JNDI名称空间中查找ejb对象的替代方法。因此,对于获得的EJB,@ EJB注释没有什么特别的。



因此,基于EJB 3.0 Spec,使用@EJB从servlet中获取ejb是一种标准实践。注释。


We all know that in the web tier there is the possibility that only a single instance of a given Servlet exists which services multiple requests. This can lead to threading issues in instance variables.

My question is, is it safe to inject an EJB using the @EJB annotation into a servlet as an instance variable?

My initial instinct would be no, under the assumption that the same instance of the EJB would service multiple requests at the same time. It would seem that this would also be the instinct of a number of other programmers: Don't inject to servlets

However have I jumped to the wrong conclusion. Clearly what is injected into the servlet is a proxy, under the hood does the container actually service each request with a different instance and maintain thread safety? As this forum would suggest: Do inject to servlets

There seems to be a lot of conflicting opinions. WHICH IS CORRECT???

解决方案

Your reference "Don't inject to servlets" mentions nothing about ejbs or @ejb annotation. It talks about not thread safe objects such as PersistenceContext.

Per EJB spec you can access ejbs from variety of remote clients including servlets (EJB 3.0 Specification (JSR-220) - Section 3.1). Injecting ejb using @EJB annotation is a method of obtaining EJB interface via dependency injection (section 3.4.1) which is alternative to looking up ejb objects in the JNDI namespace. So there is nothing special about @EJB annotation with respect to EJBs obtained.

So, based on EJB 3.0 Spec, it's a standard practice to obtain ejbs from servlets using @EJB annotation.

这篇关于将EJB作为实例变量注入到servlet中是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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