'Does Guice have an annotation similar to Spring's @Mandatory or @Required?

Guice does not require initialization of provides methods in the modules, allowing the service to start running without these consumers initializing, which can result in major issues after an outage.

Is there a way to require this initialization - similar to @Mandatory or @Required in Spring?

If not, how would we make initialization mandatory?

The code itself probably won't add anything, but here's a general version of what we are trying to ensure initicalizes within the module itself:

@Provides
@Singleton
public TriggeredConsumer triggeredConsumer(variousParameters) {
    TriggeredConsumer triggeredConsumer = new TriggeredConsumer(variousParameters);

    triggeredConsumer.start();
    shutdownHook.thenRun(triggeredConsumer::stop);

    return triggeredConsumer;
}


Solution 1:[1]

The question refers to lazy vs. eager initialisation.

@Provides
@Singleton

Is executed only, if the provided binding is requested to be injected somewhere else due to lazy initialisation in DEVELOPMENT stage.

Caused by the bug provider methods can't bind eager singletons in Guice, eager initialisation is only possible within the configure method of a Guice module as documented for Eager Singletons

bind(TriggeredConsumer.class).asEagerSingleton();

or by creating the injector in PRODUCTION stage: Phase 3: Singleton Preloading:

Injector injector = Guice.createInjector(Stage.PRODUCTION, new MyGuiceModule());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jens Vagts