Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Singleton Session Bean into a Stateless Session Bean

Is it allowed (and good practice) to hold some shared informations in our application by using a Singleton Session Bean inside a Stateless Session Bean?

The SSB will be injected into the SLSB.

@Stateless
public class MySLSB {

    @Inject
    MySSB mySSB;

-

@Singleton
@Lock(READ)
public class MySSB implements Serializable {

    private static final long serialVersionUID = 1L;
like image 813
Gatschet Avatar asked Aug 25 '15 06:08

Gatschet


People also ask

When to use Singleton Session Bean in Java?

1. Overview Whenever a single instance of a Session Bean is required for a given use-case, we can use a Singleton Session Bean. In this tutorial, we're going to explore the this through an example, with a Jakarta EE application. 2. Maven First of all, we need to define required Maven dependencies in the pom.xml.

What is a Stateful Session Bean?

Stateful session beans are by definition tied to a single client, so for each new client that requests its services, a new instance is created. On the other end of the spectrum is the new singleton session bean.

What happens when you inject prototype bean to Singleton Bean?

This is one of the most asked Spring interview questions. When you inject prototype bean to singleton bean, prototype bean still behave like a singleton bean. Let’s understand this with the help of example. 1.

Is it legal to store Java EE objects in singleton state?

It is legal to store Java EE objects that do not support concurrent access (e.g. Entity Managers, Stateful Session Bean references) within Singleton bean instance state. However, it is the responsibility of the Bean Developer to ensure such objects are not accessed by more than one thread at a time.


2 Answers

It is more than allowed. Using Singleton injections in your stateless or statefull EJBs would allow you to call business methods on your SSB in your SLSB. One of the trivial advantages is using SSB concurrent capabilities. In your example all of your method calls toward you SSB would be locked on Read and that means all your threads would be accessing your SSB methods on Read mode unless a thread is holding a lock on Write.

like image 161
javadev Avatar answered Nov 14 '22 21:11

javadev


Yes, it is allowed and I think it is good practice. In projects I am working with there are stored global properties read from file. It is good practice because you store it in one place and if you need these information then you only have to inject your singleton bean. I think it is good example of hollywood principle.

like image 30
wawek Avatar answered Nov 14 '22 22:11

wawek