我正在开发一个非常简单的tomcat和jersey servlet设置。我只是注意到为每个请求构造了servlet类。我读过的关于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入门类如下所示:
@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的单个实例提供多个请求?
答案 0 :(得分:2)
默认情况下,Jersey会根据请求实例化资源类。如果您只想拥有一个资源类实例,则应使用@Singleton对其进行注释。有关详细信息,请查看此SO question