Replacing GlobalSettings.onStart and onStop

I am trying to migrate my GlobalSettings to playframework 2.4, but it's hard for me to understand what I should do.

Currently my Global is similar to below, I already correctly moved onRequest to RequestHandler:

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(); } } } 
+6
source share
2 answers

I think it should be along the line (without packaging and import) ...

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" 
+11
source

As an addition to the answer. If you create an instance of the class using "asEagerSingleton ()", and it depends on whether the playback application has already been started, you must "@Inject ()" the application in your class constructor to make sure that it is available.

My problem is with 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 found the answer in this forum [Play 2.4] Initialize code after running the application

+3
source

Source: https://habr.com/ru/post/988577/


All Articles