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
?
You need to use constructor injection in your ApplicationStart class and provide an ApplicationModule to bind it eagerly.
In your application.conf:
play.modules.enabled += "yourPath.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();
}
}
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
}
}
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);
});
}
}
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