尝试使用Web服务时,会抛出NullPointerException,并且应用程序日志中缺少预期的日志语句。
我在以下代码中得到NullPointerException:
public void useWebservice() {
initEndpoint();
try {
port.usefulFunctionWebserviceProvides(); // NullPointerException is thrown here!
} catch (javax.xml.ws.soap.SOAPFaultException ex) {
log.error("Something went wrong making a request to the webservice");
}
}
initEndpoint方法如下所示:
private volatile Webservice service = null; // instance variable
private WebservicePort port = null; // instance variable
private void initEndpoint() {
String username = "username"; // Loaded from a properties file
String password = "password"; // Loaded from a properties file
LoginResponse loginResponse;
Webservice theService = service;
if (theService == null || port == null) {
synchronized (this) {
theService = service;
if (theService == null) {
try {
log.info("Initializing Endpoint (service & port)"); // This line appears in the log
service = new Webservice();
port = service.getWebservicePort();
final String wsdlUrl = properties.getProperty(WSDL_URL, WSDL_DEFAULT_URL);
((BindingProvider)port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, wsdlUrl);
log.info("EndpointAddress set");
LoginRequestType loginRequest = new LoginRequestType();
loginRequest.setUsername(username);
loginRequest.setPassword(password);
loginResponse = port.login(loginRequest, null, null);
} catch (Exception e) {
try {
log.info("re-Initializing Endpoint (service & port)");
// Try to connect to the webservice using a fallback URL
} catch (Exception e2) {
log.error("Couldn't connect to webservice");
service = null;
throw new CustomException();
}
}
if (loginResponse == null) {
service = null;
throw new CustomException();
}
}
}
}
}
除了日志消息“Initializing Endpoint(service& port)”之外,没有信息记录打印到日志文件。
我不明白在useWebservice方法中port port变量如何为null。我还希望在日志文件中看到“EndpointAddress set”或“re-Initializing Endpoint(service& port)”。但两者都没有打印到文件中。
代码之前运行良好,但在移动到新项目并用作依赖项后开始出现问题。
答案 0 :(得分:0)
问题已经确定,这是一个缺失的依赖。因此,当代码尝试初始化端口时抛出了错误。 catch块仅捕获异常,以便永远不会执行代码。如果我们抓住了throwable,我们会看到来自catch块的日志语句。
PS:在问题中的initEndpoint方法中初始化端口对象是非线程安全的!需要为每个请求初始化端口。