应用程序启动后,PlayFramework 2.4运行一些代码 [英] PlayFramework 2.4 run some code after application has started

查看:41
本文介绍了应用程序启动后,PlayFramework 2.4运行一些代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在游戏2.4中,重写ApplicationLoader中的builder方法或在Abstract模块中实现EagerBinding将替换现有的游戏2.3 GlobalSettings onStart.

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

但是在播放2.3 onStart方法时,您的应用程序已经启动,并加载了所有插件/依赖项.您能否在Play 2.4中做同样的事情,即在应用程序启动后运行一段代码.

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.

就我而言,Slick要求应用程序已启动才能访问数据库.

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

谢谢

推荐答案

众所周知,当您在Module中急切地绑定一个类时,它将尝试尽快初始化它的实例.在play framework 2.4中,这是在启动应用程序之前获取运行代码的方式.

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.

但遵循DI的常见预期规则: 如果在要运行的类的构造函数中将app: Application作为参数(也称为对...的依赖")添加,则它将在应用程序启动后执行;否则,它将在应用程序中执行.像这样:

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

}

这是合乎逻辑的,因为任何有价值的DI框架都可以计算出他可以按什么顺序注入哪些类.

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

然后在您的模块中只需添加通常的绑定(此处为playframework样式,而不是Guice):

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

bind[MyInitCodeClass] toSelf eagerly()

希望这行得通.停止使用Play.current并仅使用Play 2.4的新DI系统注入应用程序也很有用.

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.

我想在 playframework纠缠室上为@easel表示感谢,以帮助我解决这一问题

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

这篇关于应用程序启动后,PlayFramework 2.4运行一些代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆