§Embedding a Play server in your application
While Play apps are most commonly used as their own container, you can also embed a Play server into your own existing application. This can be used in conjunction with the Twirl template compiler and Play routes compiler, but these are of course not necessary, a common use case for embedding a Play application will be because you only have a few very simple routes.
The simplest way to start an embedded Play server is to use the Server
factory methods. If all you need to do is provide some straightforward routes, you may decide to use the Routing DSL, so you will need the following imports:
import play.routing.RoutingDsl;
import play.server.Server;
import static play.mvc.Controller.*;
Then you can create a server using the forRouter
method:
Server server =
Server.forRouter(
(components) ->
RoutingDsl.fromComponents(components)
.GET("/hello/:to")
.routeTo(to -> ok("Hello " + to))
.build());
By default, this will start a server on a random port in test mode. You can check the port using the httpPort
method:
CompletionStage<WSResponse> response =
ws.url("http://localhost:" + server.httpPort() + "/hello/world").get();
You can configure the server by passing in a port
and/or mode
:
Server server =
Server.forRouter(
(components) ->
RoutingDsl.fromComponents(components)
.GET("/hello/:to")
.routeTo(to -> ok("Hello " + to))
.build());
To stop the server once you’ve started it, simply call the stop
method:
server.stop();
Note: Play requires an application secret to be configured in order to start. This can be configured by providing an
application.conf
file in your application, or using theplay.http.secret.key
system property.