在Play应用程序中启动时调用服务 [英] Calling a service on startup in a Play application
问题描述
我有一个Play 2.4应用程序.尝试在应用程序启动时启动每周任务.当前的建议是在构造器中为急切注入的类(Guice)执行此操作.但是,我的任务需要访问服务.如何在不出错的情况下将该服务注入我的任务:
I have a Play 2.4 application. Trying to kick off a weekly task when application starts. The current recommendation is to do that in a constructor for an eagerly injected class (Guice). However, my task needs access to a service. How can I inject that service into my task without getting an error:
Error injecting constructor, java.lang.RuntimeException: There is no started application
?
推荐答案
您需要在ApplicationStart类中使用构造函数注入,并提供ApplicationModule来对其进行热切绑定.
You need to use constructor injection in your ApplicationStart class and provide an ApplicationModule to bind it eagerly.
在您的application.conf中:
In your application.conf:
play.modules.enabled += "yourPath.AppModule"
在您的AppModule类中:
In your AppModule Class:
public class AppModule extends AbstractModule {
@Override
protected void configure() {
Logger.info("Binding application start");
bind(ApplicationStart.class).asEagerSingleton();
Logger.info("Binding application stop");
bind(ApplicationStop.class).asEagerSingleton();
}
}
在您的ApplicationStart类中:
In your ApplicationStart class:
@Singleton
public class ApplicationStart {
@Inject
public ApplicationStart(Environment environment, YourInjectedService yourInjectedService) {
Logger.info("Application has started");
if (environment.isTest()) {
// your code
}
else if(
// your code
}
// you can use yourInjectedService here
}
}
万一您需要它; ApplicationStop:
In case you need it; ApplicationStop:
@Singleton
public class ApplicationStop {
@Inject
public ApplicationStop(ApplicationLifecycle lifecycle) {
lifecycle.addStopHook(() -> {
Logger.info("Application shutdown...");
return F.Promise.pure(null);
});
}
}
这篇关于在Play应用程序中启动时调用服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!