0

I am trying to understand what could be done with @Stateful beans, given @SessionScoped CDI beans. I created this JAX-RS resource:

@Path("ping")
public class PingResource {

    @Inject
    private StatelessCounter statelessCounter;

    @Inject
    private StatefulCounter statefulCounter;

    @Inject
    private SingletonCounter singletonCounter;

    private long jaxrsCounter;

    @GET
    @Path("/counter")
    public String incrementAndGetCounter() {
        statelessCounter.incrementCounter();
        statefulCounter.incrementCounter();
        singletonCounter.incrementCounter();
        jaxrsCounter++;

        return statelessCounter.getCounter() + " " + statefulCounter.getCounter() + " " + singletonCounter.getCounter() + " " + jaxrsCounter;
    }
}

Just to understand behavior of stateful bean. But, everytime I call /counter endpoint, I always get a fresh statefulCounter. I just want to know what is the criteria for the EJB container to return same stateful object used before; as it is stateful, there must be a way to get the same old object.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Prakhar Mishra
  • 1,586
  • 4
  • 28
  • 52
  • The server doesn't do that, the client is responsible for maintaining the stateful bean instance and keep communicating through that same instance. So if you keep getting a different instance in your sessionScoped bean then I question if the sessionScoped bean itself is properly maintained. It sounds like a new one is created for each invocation of /counter. – Gimby Jan 07 '20 at 12:02
  • Actually, I haven't marked my resource `/counter` as `@SessionScoped`. Its `@RequestScoped` only (default scope). I am trying to figure out why (in which case) should I use **@Stateful** EJB to maintain a shopping cart instead of **@SessionScoped** CDI bean. – Prakhar Mishra Jan 07 '20 at 12:07

0 Answers0