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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With