Search code examples
javaejbjax-rscdi

How to propagate same instance using CDI


I have a web application with JAX-RS, CDI and EJB. In each resource I inject a Stateless SessionBean, and my question is whether it is possible to inject the same instances into a provider of JAX-RS and the Stateless SesionBean. I am trying to pass some data that come in each request to the Stateless SesionBean from a ContainerRequestFilter. All EJB components are accessed only by jax rs resources.

Example:

public class Bean {
    private String attr;

    // getter and setter
}

@Stateless
public class BeanService {

    @Inject
    Bean bean;

    public void doStuff() {
        bean.getAttr();
        // do something with bean.attr
    }
}

@Path("/bean")
public class BeanResource {

    @Inject
    BeanService service;

    @GET
    public void doStuff() {
        service.doStuff():
    }
}

@Provider
public class BeanRequestFilter implements ContainerRequestFilter {

    @Inject
    Bean bean;

    @Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException {
        String data = null; // <- get data from request
        bean.setAttr(data);
    }
}

Update

Change the Bean for Pojo, my only intention is use a class that hold some state that come in every request and can be transmited in each invocation, since the PojoResource to PojoService. I want to do it in this way because all the services retrive this data and I don't want to pass this as parameter on every method.


Solution

  • This looks like your Bean class is essentially request scoped, so changing it to:

    @RequestScoped
    public class Bean {
        ...
    }
    

    should have the desired effect. The same instance will be injected in both the BeanRequestFilter and the BeanService.

    However, I think you may also get what you're looking for by injecting the ContainerRequestContext directly into the BeanService and forgetting about Bean altogether.

    @Stateless
    public class BeanService {
    
       @Context
       ContainerRequestContext containerRequestContext;
    
       public void doStuff() {
          // <- get data from request
       }
    }