I want to bind a class to an instance but Guice won't let me, giving me the Binding points to itself error. I also want the instance to be a singleton.
So to give a bit more background. I have a class that I want to bind, but I can't since the bindClass and the instanceClass has to be different.
//This fails when bindClass==instanceClass
bind((bindClass)).to(instanceClass).in(Singleton.class);
There is a question with the title "Guice Beginner - How to bind concrete classes" that can be found here:
Guice Beginner - How to bind concrete classes?
The accepted answer is to not bind and the let the "Just In Time" binding do the job.
But what if you want a singleton of the instance, how do you do that?
// eager singleton always
bind(YourClass.class).asEagerSingleton();
// eager in prod, lazy in dev
bind(YourClass.class).in(Singleton.class);
This is listed, along with many other variations on the bind
statement, on the Binder class-level docs:
bind(ServiceImpl.class).in(Singleton.class); // or, alternatively bind(ServiceImpl.class).in(Scopes.SINGLETON);
Either of these statements places the ServiceImpl class into singleton scope. Guice will create only one instance of ServiceImpl and will reuse it for all injection requests of this type. Note that it is still possible to bind another instance of ServiceImpl if the second binding is qualified by an annotation as in the previous example. Guice is not overly concerned with preventing you from creating multiple instances of your "singletons", only with enabling your application to share only one instance if that's all you tell Guice you need.
Though it would also work to simply mark the class with @Singleton
and rely on JIT bindings, there are advantages to placing the binding in a Module in terms of Guice validating your graph and eagerly performing initialization. This can be especially useful in server contexts, because it is more likely that your initialization can happen before you start redirecting live traffic to your newly-loaded server instance.
See more about eager/lazy singleton loading on the Scopes wiki page.