Search code examples
javadependency-injectionguice

Two singletons instances with dependency injection (Google Guice)


I am working on a project using Depedency injection Google Guice Framework.

It's possible to bind a class with the singleton scope, in Guice as:

bind(Foo.class).to(FooImpl.class).in(Scopes.SINGLETON);

If FooImpl class is itself a real singleton class as:

public class FooImpl implements Foo{
    public static final FooImpl INSTANCE = new FooImpl();
    public static FooImpl getInstance(){...}
    // ...
}

or

public class FooImpl implements Foo{
    private FooImpl instance = null;

    private FooImpl(){...}
    public static FooImpl getInstance(){
         if(instance == null)
             instance = new FooImpl();
         return FooImpl();
         // ...
    }

    // ...
}

So, It's could be possible to declare two singletons in the project, the first one declared by Guice and the second one by the getInstance() traditionnal way.

Google Guice can also bind Interfaces to particular instance with the toInstance() method.

So, instead binding with the Singleton scope, shouln't be a better way to bind Singleton, in Java with this declaration:

bind(Foo.class).toInstance(FooImpl.getInstance());

instead of the first one? Is it more secure? Is it possible to have two singletons instances in that way?

What's the best way for declaring singletons with Google Guice?


Solution

  • The first approach you suggest is preferred:

    bind(Foo.class).to(FooImpl.class).in(Scopes.SINGLETON);
    

    This allows Guice to perform dependency injection in FooImpl as needed. This is not possible when manually binding to an instance using toInstance() as in your last suggestion.

    Finally, the Singleton design pattern is an anti-pattern for many reasons. Note that this refers to the implementation using getInstance() and so on; having a single instance of a class for the lifetime of your app (like objects in Guice's SINGLETON scope) is not bad by any means.

    Also see Guice's page on scopes for some usage guidelines of the singleton scope.