Jersey servlet class 是用每个请求构建的

Jersey servlet class is constructed with every request

我正在对 tomcat 和 jersey servlet 进行非常简单的设置。我刚刚注意到为每个请求构建的 servlet class。我读到的关于 servlet 的内容是它们是 init() 一次,service() 多次和 destroy() 一次。为什么我的设置不是这样。

下面是我的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>

我的 servlet 条目 class 如下所示:

@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();
    }
}

我应该怎么做才能让 ContactDropboxService 的单个实例服务于多个请求?

默认情况下,Jersey 将为每个请求实例化资源 class。如果你只想拥有一个资源实例class,你应该用@Singleton 注释它。有关详细信息,您可以查看此 SO question