PlayFramework 2.4 run some code after application has started

我们两清 提交于 2019-12-12 08:44:12

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/31457536/playframework-2-4-run-some-code-after-application-has-started

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