Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a service on startup in a Play application

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

?

like image 559
Developer Avatar asked Sep 14 '15 17:09

Developer


1 Answers

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

    }
}
like image 124
SerhatCan Avatar answered Oct 13 '22 21:10

SerhatCan