How can I make Guice create singletons by default?
At the moment ALL my classes are injected as singletons so if it was
default scope I could remove all such lines from the module:
bind(ProductsController.class).in(Singleton.class);
bind(ProductService.class).in(Singleton.class);
...
Look at the Spring for example - singleton is the default scope in
Spring and it is correct, because we usually use injection for high
level services, controllers and other singletons. If we need new
instance every time we just use new, we do not usually need IOC for
that. So it is very strange for me that Guice's default scope is
"new".
Can I change this?
Thanks in advance!
--
You received this message because you are subscribed to the Google Groups "google-guice" group.
To post to this group, send email to google...@googlegroups.com.
To unsubscribe from this group, send email to google-guice...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-guice?hl=en.
Can I change this?
Thanks in advance!
--
You received this message because you are subscribed to the Google Groups "google-guice" group.
To post to this group, send email to google...@googlegroups.com.
To unsubscribe from this group, send email to google-guice...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-guice?hl=en.
Imho this is a good default because it is the safest one. Being
explicit about whether something is a singleton forces developers to
think about the consequences. It may also be more efficient for
objects that are cheap to construct.
If you want everything to be bound as a singleton but without much
pre-registration, how about using classpath scanning? There's a nice
utility class in sitebricks
(http://www.google.com/codesearch/p?hl=en#iHNmFuHrx4M/trunk/sitebricks/src/main/java/com/google/sitebricks/Classes.java&q=classes%20package:http://google-sitebricks%5C.googlecode%5C.com&sa=N&cd=1&ct=rc)
that makes this easy to do, and if your services follow a naming
pattern or implement a certain interface you could scan on that and
bind everything you find as a singleton. Quite possibly this is
horrible to Guice's developers, but it works and is easy to implement.
Eelco
Module newModule = Modules.rewrite(new MyModule())
.withScope(new NoScopeMatcher(), Scopes.SINGLETON)
.build();
Sam
You cannot compare Guice's "new" to constructor's "new".
Whether singleton scope, no scope or whatever scope, Guice will inject
all the dependencies for you, which is not the case when you just call
the constructor.
One should not mix application with "new" here or there (excluding
leaf objects), here is why:
http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/
I am not sure, but I suppose that in my application "no scopes" are
even more common that singletons.