Question

I would like to show the results of the execution of the following code based on EJB:

@Stateless
public class StatelessBean implements IsStatelessBean{
...
}

@Stateful
public class StatefulBean implements IsStatefulBean{
...
}

@Singleton
public class SingletonBean implements IsSingletonBean{
...
}

@Stateless
public class MyBean {

@EJB
IsStatelessBean slBean1;
@EJB
IsStatelessBean slBean2;
@EJB
IsStatefulBean sfBean1;
@EJB
IsStatefulBean sfBean2;
@EJB
IsSingletonBean singlBean1;
@EJB
IsSingletonBean singlBean2;



    public String checkStatelessEqual() {
        String areEqual;
        if(slBean1.equals(slBean2))
            areEqual = "are equal!";
        else
            areEqual = "are NOT equal!";

        return "Stateless Beans "+areEqual;
    }


    public String checkStatefulEqual() {
        String areEqual;
        if(sfBean1.equals(sfBean2))
            areEqual = "are equal!";
        else
            areEqual = "are NOT equal!";

        return "Stateful Beans "+areEqual;
    }


    public String checkSingletonEqual() {
        String areEqual;
        if(singBean1.equals(singBean2))
            areEqual = "are equal!";
        else
            areEqual = "are NOT equal!";

        return "Singleton Beans "+areEqual;
    }

}

When I call the methods from the client the results are:

Stateless Beans are equal!
Stateful Beans are NOT equal!
Singleton Beans are equal!

I expected the Singleton Beans to be equal, but I did not expect the result for Stateless and Stateful.

  1. Is it only a coincidence in this case that the Container gets the same instance of Stateless bean from the pool?
  2. What is right about Stateful? Although they have only one client, is a new different reference created when a client injects it more than once?

Hint: The equals method is not overrided, consequently the only references are compared.

Était-ce utile?

La solution

That's the expected behavior.

Regarding the stateless bean, from the ejb 3.1 spec (Sec. 3.4.7.1):

All business object references of the same interface type for the same stateless session bean have the same object identity...

and for the stateful bean, from the ejb 3.1 spec (Sec. 3.4.7.2):

Stateful session bean references ... to different session bean instances will not have the same identity.

It makes sense, if you stick to the contract, you are guaranteed that invoking a business method on any of two instances of a stateless bean, will have the exact same effects, with a stateful bean that is not necessarily true.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top