简体   繁体   中英

What kind of “pattern” to use for getting SOAP Client? Web Application / Enterpise Application

I am wondering whether to use singleton pattern to get SOAP client instance?

Is singleton pattern a good solution for that problem. I don't want to create a new client for every WS invocation.

I have two applications in which I've encountered the same problem. One is web application written in JSF. Other is Enterpise Application written with usage of EJB.

Current simplified implementations:

Web Application:

public final class ClientWs {

  private WS port;

  public ClientWs(String wsdlAddress) throws ClientWsException {
    setPort(wsdlAddress);
  }
  ...
}


@Named
@ApplicationScoped
public class ClientBean {
  ...
  public ClientWs getClient() {
    return new ClientWs(URL);
  }
  ...
}

Enterpise Application:

public final class ClientWs {

  private WS port;

  public ClientWs(String wsdlAddress) throws ClientWsException {
    setPort(wsdlAddress);
  }
  ...
}

@Singleton(name = "clientBean")
public class ClientBean {
  ...
  public ClientWs getWsClient() {
    return new ClientWs(URL);
  }
  ...
}

What would be your solution for getting instance client? Would you use different approaches for those kinds of applications?

I don't think you really need worry that much about it being a Singleton or not if you keep the client stateless and let it be managed by your DI framework/container (eg Spring, CDI or whatnot). You could use Spring-WS and just get the instance from the applicationcontext. It is a Singleton by default but you are typically not aware of, nor concerned about that.

EDIT: The implementation as shown above is not stateless. It depends on the URL which is provided at creation time. So a vanilla singleton implementation would suffer from the problem that you can no longer use the client class to access any other web service. If you want to keep going this route then you could create a Factory which manages internally a single instance of each client per URL, possibly in a Map.

However, as I mentioned, I advise to leave this part of the lifecycle management to a framework instead of rolling your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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