NullPointer Exception while calling webservice in play framework

╄→尐↘猪︶ㄣ 提交于 2020-01-06 07:05:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!