EJB3: stateful bean: How to access first instance created on jndi lookup

466 Views Asked by At

My code:

@Local
public interface IA{

   public void setX(String x);

   public String getX();


}

@Stateful
@LocalBinding(jndiBinding="a/b/c")
public class BC implements IA{

private String value;p

  @Override
  public void setX(String x) {
    this.value = x;
  }

  @Override
  public String getX() {
    return this.value;
  }

}

I look up the bean, then set x. then a response is sent back to the client. The client fires a new request, as a part of handling this request i need to look up the data set previously. This is how i did it

InitialContext ic = new InitialContext();
IA ia= (IA)ic.lookup("a/b/c");
String x = ia.getX();

At this point when i log string x, i get null. I checked the jmx console to see whether a new instance is created, and it does get created. every time a look up is done, a new instance is created.

What i need is to access the previously set value. is this possible ?

2

There are 2 best solutions below

2
On

New instance (Object) will have there own set of values or state. Because they are independent to each other. like you said:

I look up the bean, then set x. then a response is sent back to the client. The client fires a new request, as a part of handling this request i need to look up the data set previously.

You can get the value earlier and set it to object separately like:

InitialContext ic = new InitialContext();
IA ia= (IA)ic.lookup("a/b/c");
String x = ia.setX(OldValue);

I suppose this is separate method as:

String oldvalue = oldObj.getX();
fireNewRequest(oldValue);
2
On

This is working as intended: each lookup of the stateful session bean will return a new instance. If you want to save the instance, you need to store the ia somewhere. (And if you don't want to save the instance, you need to invoke an @Remove method to avoid wasting memory. The EJB container should eventually time out the instance, but it's best to remove it promptly if you know you're done with it.)