8

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

Roy Lin
  • 730
  • 8
  • 17

2 Answers2

7

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.

le-doude
  • 3,345
  • 2
  • 25
  • 55
  • Hey thanks for your answer, it looked very sound, but I havent actually had the time to try it out till now. I could bind the application to it, but the state of application was still not started before the code was run. I've also tried starting it myself by doing "Play.start(app)", which isn't ideal and that caused a few problems in production. – Roy Lin Aug 02 '15 at 09:22
  • This solution worked for me with Play 2.6.19 and Java, although I had to be careful not to get a dependency circle. – Itchy Oct 08 '18 at 15:42
0

Roy, didn't quite get your problem.

Do you have an issue with using an EagerBinding as you mention?

You can still use GlobalSettings onStart, beforeStart etc if you wish, its just discouraged because of the wish to move away from Global state.

jacks
  • 4,614
  • 24
  • 34
  • 1
    Hi, thanks for the response. Yes you can still use GlobalSettings onStart, but since it's deprecated and will be removed in the future, I do not wish to keep using it. The problem I am facing is that slick requires a running application before it can query the database (i.e. Play.start(app) must have been called). Using EagerBindings, I can perform a task before the application has started but not after it. Cheers – Roy Lin Jul 17 '15 at 11:31