Calling a service on startup in a Play application

放肆的年华 提交于 2019-12-10 12:49:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!