Search code examples
restjakarta-eejax-rsresteasyjboss6.x

Is a new object created always for a RestEasy webservice class?


We are using ReastEasy with JBoss EAP 6.x. I want to know if a new object is always created for every http request. If yes, how can I stop JBoss creating new objects for every request?

I annotated a void method in my web service class with javax.annotation.@PostConstruct to check if a new object is always being created. For my amusement the method itself was not called. Then I understood that the servlet container is managing my web service classes and that is why the @PostConstruct is not called. Am I right?

Can anyone please point me to some resources which explains the webservice life cycle?


Solution

  • "I want to know if a new object is always created for every http request"

    Yes. See section 3.1.1 Lifecycle and Environment, in the JAX-RS spec:

    By default a new resource class instance is created for each request to that resource.


    "If yes, how can I stop jboss creating new objects for every request?"

    One way is to override getSingletons() in Application subclass, which returns a Set of resources and providers you want to be only created once. See Resteasy Doc for more information on deployment options. For example

    @ApplicationPath("/rest")
    public class RestApplication extends Application {
        private final Set<Object> singletons = new HashSet<Object>();
    
        public RestApplication(){
            singletons.add(new SingletnResourceClass());
        }
    
        @Override
        public Set<Object> getSingletons(){
            return singletons;
        }
    }
    

    "Then I understood that the servlet container is managing my web service classes and that is why the @PostConstruct is not called. Am I right?"

    That annotation in Java EE is handled by CDI, and in JBoss, we should have a beans.xml file in the WEB-INF to enable the CDI module.


    "Can anyone please point me to some resources which explains the webservice life cycle?"

    The first link above has some explanation