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?