@Stateless vs @RequestScoped

前端 未结 2 1794
遥遥无期
遥遥无期 2020-12-28 15:42

I am learning to use JAX-RS for some restful api development and have an issue regarding my resource classes.

My understanding is that my resource class should be R

相关标签:
2条回答
  • 2020-12-28 16:03

    Matthias is spot on.

    A @Stateless annotated bean is an EJB which by default provides Container-Managed-Transactions. CMT will by default create a new transaction if the client of the EJB did not provide one.

    Required Attribute If the client is running within a transaction and invokes the enterprise bean’s method, the method executes within the client’s transaction. If the client is not associated with a transaction, the container starts a new transaction before running the method.

    The Required attribute is the implicit transaction attribute for all enterprise bean methods running with container-managed transaction demarcation. You typically do not set the Required attribute unless you need to override another transaction attribute. Because transaction attributes are declarative, you can easily change them later.

    In the recent java-ee-7 tuturial on jax-rs, Oracle has example of using EJBs (@Stateless).

    ... the combination of EJB's @javax.ejb.Asynchronous annotation and the @Suspended AsyncResponse enables asynchronous execution of business logic with eventual notification of the interested client. Any JAX-RS root resource can be annotated with @Stateless or @Singleton annotations and can, in effect, function as an EJB ..

    Main difference between @RequestScoped vs @Stateless in this scenario will be that the container can pool the EJBs and avoid some expensive construct/destroy operations that might be needed for beans that would otherwise be constructed on every request.

    0 讨论(0)
  • 2020-12-28 16:05

    When you don't want to make your root resource as an EJB (by annotating it with @Stateless), you can use a UserTransaction.

    @Path("/things")
    @RequestScoped
    public class ThingsResource{
    
        @POST
        @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
        public Response create(final Thing thing){
            utx.begin();
            em.joinTransaction();
            final ThingEntity thingEntity = new ThingEntity(thing);
            em.persist(thing);
            utx.commit();
            final URI uri = uriInfo.getAbsolutePathBuilder()
                .path(Long.toString(thingEntity.getId())).build();
            return Response.created(uri).build();
        }
    
        @PersistenceContext(unitName = "somePU")
        private transient EntityManager em;
    
        @Resource
        private transient UserTransaction ut;
    
        @Context
        private transient UriInfo uriInfo;
    }
    
    0 讨论(0)
提交回复
热议问题