PlayFramework 2.4 run some code after application has started

对着背影说爱祢 提交于 2019-12-04 03:27:34

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.

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.

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