0

I Have a rest app created with Jersey framework I'm trying to inject Stateful bean into my rest controller, but this bean always is created again. I'v tested this by passing test data into this bean after printing past data, but sout always printing null.

@Stateful
public class TestService {
   private String test;

   public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }
}

@Path("/testController")
public class TestController {

    @EJB
    private TestService testService;
    
    @Path("/getTest/")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getPage(@QueryParam("TEST")String test) {
        
        System.out.println(testService.getTest());
        testService.setTest(test);

    }
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Bogus
  • 283
  • 1
  • 2
  • 13
  • 1
    A stateful EJB lives as long as its client. A JAX-RS resource is essentially request scoped. However, it's really difficult to post a proper answer for the actual X of your http://xyproblem.info, because you're basically violating the "S" part of "REST". That "S" stands for "Stateless" and not for "Stateful". – BalusC Feb 07 '21 at 10:20

1 Answers1

0

REST stands for Representational State Transfer. The "S" stands for State not "Stateless".

State Transfer: because REST Services are meant to tranfer the state of entities from client to server or vice versa.

Nevertheless REST Components have a stateless nature.

They are not bound to a specific client. BUT Stateful Session Beans are bound to a specific client. A stateful instance can for example be destroyed if the bound client stays inactive for an amount of time.

you try to inject a stateful session bean in a stateless component. This is not possible or at least not consisent at all.

A use case for the practice when you are using CDI (best issue):

  • Inject your Stateful Session Bean in a @SessionScoped CDI Bean.
  • Do not forget to setup CDI correctly: simplest way is to create the \WEB-INF\beans.xml file and set bean-discovery-mode="all".

Another use case when you are not using CDI:

  • Make a JNDI Lookup for the Stateful Session Bean and save the return (proxy) as a HttpSession-Attribute
Lejmi
  • 3
  • 4