I'm trying to migrate my GlobalSettings to playframework 2.4 but I'm having a hard time understanding what I'm supposed to do.
Currently my Global is like below, I already moved out the onRequest to the RequestHandler properly:
public class Global extends GlobalSettings {
private BackgroundTasks backgroundTasks;
@Override
public void onStart(Application arg0) {
Logger.info("Starting background tasks");
backgroundTasks = new BackgroundTasks();
}
@Override
public void onStop(Application arg0) {
Logger.info("Stopping background tasks");
backgroundTasks.shutdown();
super.onStop(arg0);
Logger.info("Saving modules data");
for(Module m: controllers.Application.modules){
m.saveData();
}
}
}
I think it should be along the line of (without package & imports)...
OnStartModule.java:
public class OnStartModule extends AbstractModule {
@Override
protected void configure() {
bind(BackgroundTasks.class).asEagerSingleton();
}
}
BackgroundTasks.java:
@Singleton
public class BackgroundTasks {
@Inject
public BackgroundTasks(ApplicationLifecycle lifecycle) {
lifecycle.addStopHook(() -> {
Logger.info("Stopping background tasks");
this.shutdown();
Logger.info("Saving modules data");
for(Module m: controllers.Application.modules){
m.saveData();
}
return F.Promise.pure(null);
});
}
}
application.conf:
play.modules.enabled += "OnStartModule"
Just as an addendum to the answer. If you instantiate a class using the 'asEagerSingleton()' and it depends the play application to have been already started then you must '@Inject()' the application into your class constructor to ensure it is available.
My issue was due to my old code (pre 2.4) using the static 'import play.api.Play.current' instead of passing the play application object as a constructor argument.
I discovered the answer in the this forum post [Play 2.4] Initialise code after Application has started
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With