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

Dev*_*per 10 service dependency-injection guice playframework

我有一个Play 2.4应用程序.在应用程序启动时尝试启动每周任务.目前的建议是在一个急切注入的类(Guice)的构造函数中这样做.但是,我的任务需要访问服务.如何在不出错的情况下将该服务注入我的任务:

Error injecting constructor, java.lang.RuntimeException: There is no started application
Run Code Online (Sandbox Code Playgroud)

Ser*_*Can 4

您需要在 ApplicationStart 类中使用构造函数注入并提供一个 ApplicationModule 来急切地绑定它。

在你的 application.conf 中:

play.modules.enabled += "yourPath.AppModule"
Run Code Online (Sandbox Code Playgroud)

在您的 AppModule 类中:

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();

    }
}
Run Code Online (Sandbox Code Playgroud)

在您的 ApplicationStart 类中:

@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

    }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要的话;申请站:

@Singleton
public class ApplicationStop {

    @Inject
    public ApplicationStop(ApplicationLifecycle lifecycle) {

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

    }
}
Run Code Online (Sandbox Code Playgroud)