Jersey是一款优秀的webservice框架,它同时支持soap和rest两种协议,而且系出名门(oracle)。美中不足的是:Jersey是基于Servlet实现的,具有Servlet的单例特性,有线程安全问题的隐患(这点跟Struts1.x很像)。
通过将Jersey与Spring整合,利用Spring托管Jersey服务实例的生成,即针对每一个客户端请求都生成一个服务实例,可以很好的解决Jersey的单实例问题。
本文不再赘述Jersey与Spring的整合,只讲解如何让Spring针对每一个请求(request)都生成新的Jersey服务实例,具体方法有如下两种:
(1) request scope:
1 @Component 2 @Scope("request") 3 @Path("/WebServiceDemoImpl") 4 public class WebServiceDemoImpl implements WebServiceDemo{
加入@Scope("request")注解后,Spring会针对每一个request请求都生成新的Jersey服务类实例。但使用request scope还要在web.xml文件中加入Spring RequsetContextListener的配置:
1 <web-app> 2 ... 3 <listener> 4 <listener-class>org.springframework.web.context.request.RequestContextListen er</listener-class> 5 </listener> 6 ... 7 </web-app>
(2) prototype scope(推荐):
1 @Component 2 @Scope("prototype") 3 @Path("/WebServiceDemoImpl") 4 public class WebServiceDemoImpl implements WebServiceDemo{
加入@Scope("prototype")注解后,Spring会针对每一个request请求都生成新的Jersey服务类实例。使用此方法不需要配置Spring RequsetContextListener,较为简便,推荐!