问题
Anything wrong in this program ?
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();
}
}
回答1:
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.
Controller:
public class SampleController extends Controller {
@Inject Sample sample;
public Promise<Result> apiCall() {
sample.callApi();
return promise(() -> ok());
}
}
Interface:
@ImplementedBy(SampleImpl.class)
public interface Sample {
public void callApi();
}
And the interface implementation:
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();
}
}
Reference docs: https://www.playframework.com/documentation/2.4.x/JavaDependencyInjection#Binding-annotations
来源:https://stackoverflow.com/questions/32880830/nullpointer-exception-while-calling-webservice-in-play-framework