在 Play 应用程序中启动时调用服务

Calling a service on startup in a Play application

我有一个 Play 2.4 应用程序。尝试在应用程序启动时启动每周任务。当前的建议是在构造函数中为急切注入的 class (Guice) 执行此操作。但是,我的任务需要访问服务。如何在不出现错误的情况下将该服务注入到我的任务中:

Error injecting constructor, java.lang.RuntimeException: There is no started application

?

您需要在 ApplicationStart 中使用构造函数注入 class 并提供一个 ApplicationModule 来预先绑定它。

在你的application.conf中:

play.modules.enabled += "yourPath.AppModule"

在你的 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 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

    }
}

以备不时之需;应用程序停止:

@Singleton
public class ApplicationStop {

    @Inject
    public ApplicationStop(ApplicationLifecycle lifecycle) {

        lifecycle.addStopHook(() -> {
            Logger.info("Application shutdown...");
            return F.Promise.pure(null);
        });

    }
}