javatomcatservletsglassfishservlet-container

Jersey servlet class is constructed with every request


I am working on a very simple setup of tomcat and jersey servlet. I just noticed that servlet class constructed for every request. What I have read about servlets is that they are init() once, service() multiple times and destroy() once. Why is it not the case for my setup.

Below is my web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <servlet>
        <servlet-name>contact-dropbox-servlet</servlet-name>
        <servlet-class>
            org.glassfish.jersey.servlet.ServletContainer
        </servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.inbhiwadi.services</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>contact-dropbox-servlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

And my servlet entry class looks like below:

@Path("/contact")
@Slf4j
public class ContactDropboxService {

    private ContactDAO contactDAO;

    private NotificationPublisher notificationPublisher;

    public ContactDropboxService() {
        ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
        this.contactDAO = (ContactDAO) context.getBean("contactDAO");
        this.notificationPublisher = (NotificationPublisher) context.getBean("notificationPublisher");
        log.debug("ContactDropboxService constructed one more time");
    }

    @GET
    public String greet() {
        log.info("Welcome to InBhiwadi contact services!");
        return "Welcome to InBhiwadi contact services";
    }

    @POST
    @Path("/drop")
    public Response create(Contact contact) {

        log.debug("Received contact is : [{}]", contact.toString());
        contactDAO.create(contact);
        notificationPublisher.publish(contact.toString());
        return Response.accepted("Contact dropped in box").build();
    }
}

What should I do to have single instance of ContactDropboxService serving multiple requests?


Solution

  • By default Jersey will instantiate resource class per request. If you want to have just one instance of resource class you should annotate it with @Singleton. For more details you can check out this SO question