问题描述
该程序有什么问题吗?
在版本2.4.3的播放框架中调用Web服务时出现nullPointerException
.
I am getting nullPointerException
while calling web service in play framework in version 2.4.3.
package com.enkindle.box;
import javax.inject.Inject;
import play.libs.ws.WSClient;
/**
* @author thirumal
*
*/
public class Sample {
@Inject WSClient ws;
public static void main(String[] args) {
Sample sample = new Sample();
sample.callAPI();
}
public void callAPI() {
ws.url("www.thomas-bayer.com/sqlrest/CUSTOMER/").get();
}
}
推荐答案
问题是您的Sample
类在依赖项注入的上下文中不可用-我假设是Guice.有几种方法可以解决此问题,但最简单的方法是使用Guice创建Sample
接口并绑定其实现SampleImpl
,以便可用于注入的依赖项.我将假设这是从控制器中产生的,因此您可以将Sample
注入到控制器中,然后从那里点击callApi()
方法.
The issue is that your Sample
class is not available within the context of your dependency injection - I'm assuming Guice. There are a couple ways to tackle this but the easiest is to create a Sample
interface and bind its implementation, SampleImpl
, using Guice so that it will be available for injected dependencies. I'm going to assume that this gets spawned from a controller, so you could inject Sample
into your controller and hit the callApi()
method from there.
控制器:
public class SampleController extends Controller {
@Inject Sample sample;
public Promise<Result> apiCall() {
sample.callApi();
return promise(() -> ok());
}
}
接口:
@ImplementedBy(SampleImpl.class)
public interface Sample {
public void callApi();
}
接口实现:
public class SampleImpl implements Sample {
@Inject WSClient ws;
@Override
public void callApi() {
// ws should not be null
ws.url("www.thomas-bayer.com/sqlrest/CUSTOMER/").get();
}
}
参考文档: https://www.playframework.com/documentation /2.4.x/JavaDependencyInjection#Binding-批注
这篇关于在播放框架中调用Webservice时发生NullPointer异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!