Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PlayFramework 2.4 run some code after application has started

In play 2.4, overriding the builder method in ApplicationLoader or implementing EagerBinding in Abstract module replaces the existing play 2.3 GlobalSettings onStart.

However in play 2.3 the onStart method, your application is already started with all the plugins/dependencies loaded. Can you do the same in play 2.4, i.e. run a piece of code after the application has started.

In my situation, Slick requires the application to have started before it can access the database.

Thanks

like image 753
Roy Lin Avatar asked Jul 16 '15 14:07

Roy Lin


1 Answers

It is common knowledge that when you bind a class eagerly in a Module it will try to initialise an instance of it as soon as possible. In play framework 2.4 this is how you get run code before application is started.

But following common expected rules of DI: If, in the constructor of the class you want to run, you add as a parameter (aka "a dependency to") to app: Application then it will be executed after the app is started; like so:

import play.api.Application
import javax.inject.Inject

class MyInitCodeClass @Inject() (val app: Application) {

//YOUR CODE HERE

}

This is logical as any DI framework worth its salt will work out which classes he can inject in which order.

Then in your module just add the usual binding (here playframework style instead of Guice):

bind[MyInitCodeClass] toSelf eagerly()

Hope this works. It is also useful to stop using Play.current and just inject the app instead using the new DI system of Play 2.4.

I would like to give credits to @easel on the playframework gitter room for helping me with that one.

like image 164
le-doude Avatar answered Oct 21 '22 13:10

le-doude