Is it safe to inject an EJB into a servlet as an instance variable?

前端 未结 4 1247

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 issu

4条回答
  •  梦谈多话
    2021-02-07 21:56

    It is safe to inject an EJB in a Servlet as a Servlet instance variable, as long as the EJB is Stateless. You MUST NEVER inject a Stateful Bean in a Servlet.

    You must implement your EJB stateless in that it doesn't hold any instance variable which itself holds a stateful value (like Persistence Context). If you need to use the persistence context, then you must get an instance of it IN the methods of the EJB. You can do that by having a PersistenceContextFactory as a EJB instance Variable and then you get an instance of the entity manager from the Factory in the method of the EJB.

    The PersistenceContextFactory is thread-safe, thus it can be injected in an instance variable.

    As long as you comply to the above mentioned rules, it should be thread-safe to inject a Stateless Bean in a Servlet

提交回复
热议问题