Reputation: 1767
I have the following piece of code taken from the official Play 2.6 docs that define a client class,
import javax.inject.Inject;
import play.libs.ws.*;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.CompletionStage;
public class MyClient implements WSBodyReadables, WSBodyWritables {
private WSClient ws;
@Inject
public MyClient(WSClient ws) {
this.ws = ws;
sendRequest();
}
public void sendRequest() {
WSRequest request = ws.url("http://example.com");
WSRequest complexRequest = request.addHeader("headerKey", "headerValue")
.setRequestTimeout(Duration.of(1000, ChronoUnit.MILLIS))
.addQueryParameter("paramKey", "paramValue");
CompletionStage<? extends WSResponse> responsePromise = complexRequest.get();
}
}
Now I have a socket actor that handles incoming socket messages. I want to fire an HTTP request every time a new message comes through the socket.
My problem is I don't know how to initialize MyClient class to use its sendRequest method.
public void onReceive(Object message) throws Exception {
if (message instanceof String) {
out.tell("I received your message: " + message, self());
MyClient a = new MyClient(); //problem here
}
}
Upvotes: 0
Views: 1219
Reputation: 12986
You must inject it, the same way you did in MyClass
:
public class MyActor extends UntypedAbstractActor {
private MyClient client;
@Inject
public MyActor(MyClient client) {
this.client = client;
}
@Override
public void onReceive(Object message) throws Exception {
client.sendRequest();
}
}
If there is some problem that dont let you use this (ex you dont control how the actor is created), add more info to your question.
Upvotes: 1