除了包含服务引用外,应用程序还需在部署时将该服务引用绑定到 JNDI 名称,便于客户端代码进行查找。现在,让我们来看一些使用和实现服务定位器模式的键类。
submitPO
方法的关键之处在于它使用了服务定位器。它使用服务定位器获取对 Web 服务的引用,然后调用该 Web 服务。public class SchemaPOServiceBD {
private ServiceLocator serviceLocator;
public SchemaPOServiceBD(){
serviceLocator = new
ServiceLocator();
}
public String
submitPO(com.sun.j2ee.blueprints.docoriented.client.PurchaseOrder po)
throws RequestHandlerException {
try {
SchemaDefinedPurchaseOrderServiceSEI
port =
(SchemaDefinedPurchaseOrderServiceSEI)
serviceLocator.getServicePort(JNDINames.SCHEMA_SERVICE_REF,
SchemaDefinedPurchaseOrderServiceSEI.class);
//convert po object into object for
service type of order
// that is to be sent to the endpoint
...
String ret =
port.submitPO(order);
return ret;
}
catch ...
....
}
}
import javax.naming.*;
import java.rmi.Remote;
import javax.xml.rpc.*;
/**
* Implements Service Locator pattern for Web services
*/
public class ServiceLocator {
private transient InitialContext ic;
public ServiceLocator() throws
ServiceLocatorException {
try {
setInitialContext();
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
}
private void setInitialContext() throws
javax.naming.NamingException {
ic = new InitialContext();
}
/**
* Service class acts as a factory of the
Dynamic proxy for the target service endpoint.
* @see java.xml.rpc.Service.java
* @return the Service instance
*/
public Remote getServicePort(String jndiName, Class
className) throws ServiceLocatorException {
try {
if
(ic == null) setInitialContext();
Service service = (Service) ic.lookup(jndiName);
return service.getPort(className);
} catch (Exception e) {
throw new ServiceLocatorException("ServiceLocator can not lookup
jndiName=" + jndiName + " and className=" + className, e);
}
}
}
package com.sun.j2ee.blueprints.docoriented.client;
public class ServiceLocatorException extends RuntimeException {
public ServiceLocatorException() {}
public ServiceLocatorException(String msg) {
super(msg); }
public ServiceLocatorException(String msg, Throwable
cause) { super(msg, cause); }
public ServiceLocatorException(Throwable cause) {
super(cause); }
}