问题
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
?
回答1:
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);
});
}
}
来源:https://stackoverflow.com/questions/32570547/calling-a-service-on-startup-in-a-play-application