简体   繁体   English

在JAX-WS或JAX-RS Web服务上共享类的实例

[英]Share an instance of a class across a JAX-WS or JAX-RS Webservice

I have built a class (call it RecordManager ) which manages data on a file system. 我建立了一个类(称为RecordManager )来管理文件系统上的数据。 I would like to make SOAP or REST calls that change the state of this class. 我想进行更改此类状态的SOAP或REST调用。 However I only want to have one instance of this class running for every call to the server. 但是,我只想让对服务器的每次调用都运行一个此类的实例。

How do I create one instance of this class and be able to use it given all JAX-WS or JAX-RS calls? 如何创建此类的一个实例,并在所有JAX-WS或JAX-RS调用下都能使用它? Ideally I would like to just call: 理想情况下,我只想致电:

 @GET 
 public ... (...){
      rec_man.update( <parameters passed by call> )
 }

where rec_man is the instance of RecordManager 其中rec_man是实例RecordManager

I'm fairly certain that I have ensured thread safety with this class. 我可以肯定地说,我已经确保此类的线程安全。

public class RecordManager {
   public static final RecordManager INSTANCE = new RecordManager();
   private RecordManager() {
         // private constructor prevents instantiation
   }
}

Your JAX-WS service or JAX-RS resource would reference RecordManager like this: 您的JAX-WS服务或JAX-RS资源将像这样引用RecordManager:

 @GET 
 public ... (...){
      ...
      rec_man = RecordManager.INSTANCE;
      rec_man.update( <parameters passed by call> )
 }

Or, if you don't like that style (singleton as a public static instance) you could hide the static instance and expose a static method to obtain it. 或者,如果您不喜欢这种样式(将单个实例作为公共静态实例),则可以隐藏该静态实例并公开一个静态方法来获取它。

public class RecordManager {
   private static RecordManager instance;
   private RecordManager() {
         // private constructor prevents instantiation
   }

   public static RecordManager getInstance() {
       if (instance == null) {
           instance = new RecordManager();
           ... init
       }
       return instance;
   }
}

Your usage becomes: 您的用法变为:

 @GET 
 public ... (...){
      ...
      rec_man = RecordManager.getInstance();
      rec_man.update( <parameters passed by call> )
 }

Note that if your instantiation logic needs to be threadsafe (eg only ever initialize once) then you could make the getInstance method synchronized or one of the techniques described in this article . 请注意,如果您的实例化逻辑必须是线程安全的(例如, 永远只能初始化一次),那么你可以做getInstance方法synchronized或描述的技术之一这篇文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM