How to make a state available to all beans in a “session”?

后端 未结 2 625
灰色年华
灰色年华 2021-01-26 12:38

I have the following design. When a client makes a request to the server, the server creates a state that holds all sorts of info. There are various stateless and stateful beans

相关标签:
2条回答
  • 2021-01-26 12:48

    Buyer beware, ThreadLocal will possibly do what you're wanting, along with a static accessor. However, this class is prone to causing memory leaks if you are not extremely careful to remove each entry at the end of the request. In addition, you seem to be using EJB; I assume they are all in the same JRE. I use ThreadLocal quite a bit in similar situations, and I've had no problems. I use SerletContextListener's to null the static reference to the ThreadLocal when the context shuts down, although that has been problematic on some older Web app servers, so I make sure the ThreadLocal exists before attempting to use it.

    EJB can "talk" to each other across servers. It sounds local all your EJB are running in the same context.

    Create a class that holds your state.

    Extend ThreadLocal--you can do this anonymously--and override initialValue() to return a new instance of your class.

    Create a utility class to hold the ThreadLocal as a static field. Don't make it final Create static fetch and remove methods that call ThreadLocal.get() and remove(). Create a static destroy() method that is called when your context shuts down--see ServletContextListener.

    0 讨论(0)
  • 2021-01-26 13:06

    I can't inject a stateful bean into a stateless bean.

    You can absolutely inject dependencies this way.

    If the stateful bean is @RequestScoped, any call into the stateless bean on that thread that hits a CDI injected contextual reference (iow proxy) will find its way to the right instance of the stateful bean.

    As long as you use CDI, you don't need to trouble yourself with trying to stash things away in your own threadlocals.

    0 讨论(0)
提交回复
热议问题