Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS: Stateless, Singleton, RequestScoped confusion

Tags:

java

jax-rs

cdi

I've seen a bunch of times several ways a JAXRS resource is configured.

I mean, sometimes I see they are annotated as @Singleton, @Stateless, @ApplicationScoped, @RequestScoped, and even without any annotation or using both of them.

  • javax.enterprise.context.RequestScoped
  • javax.enterprise.context.ApplicationScoped
  • javax.ejb.Stateless
  • javax.ejb.Singleton
  • javax.inject.Singleton

Which annotation should I use?

What has javax.ejb to do with a JAXRS resource?

By other hand, I'd also like to know about how to work exactly with @Context annotation.

I mean, I've seen this applied on a parameter, also in a class field.

@Path("entity")
public class EntityResource {

    @Context
    private Request request;

    @POST
    public Response create(Entity entity) {
        this.request...
    }

}

or,

@Path("entity")
public class EntityResource {

    @POST
    public Response create(Entity entity, @Context Request request) {
        request...
    }

}

How would i proceed?

like image 545
Jordi Avatar asked Jan 02 '23 08:01

Jordi


1 Answers

There is no need to use any EJB or CDI annotations in a JAX-RS resource class - unless you want to use EJB or CDI features in the same class.

If you want to inject any CDI bean into the resource classes, then the resource class must be a CDI bean itself, so you should add a scope annotation, preferably @javax.enterprise.context.RequestScoped.

If you use an EJB annotation like @Stateless, injection will also work, since EJBs are also CDI beans (but not the other way round). However, a stateless beans has a different lifecycle, and it is transactional by default.

On the other hand, if you need transactions, you can also use @javax.transaction.Transctional in combination with @RequestScoped and @Path.

Background:

EJBs are a bit out-dated for most purposes. They came first, before JAX-RS and CDI, but these days, CDI is regarded as the unifying dependency injection mechanism in Java EE/Jakarta EE, and older specs are in the process of being updated to get more tightly integrated with CDI.

like image 57
Harald Wellmann Avatar answered Jan 15 '23 16:01

Harald Wellmann