Author: limpbizkit
Date: Mon Jun 22 10:12:39 2009
New Revision: 1028
Added:
wiki/ToConstructorBindings.wiki
Log:
Created wiki page through web user interface.
Added: wiki/ToConstructorBindings.wiki
==============================================================================
--- (empty file)
+++ wiki/ToConstructorBindings.wiki Mon Jun 22 10:12:39 2009
@@ -0,0 +1,23 @@
+#labels Guice21
+=ToConstructor Bindings=
+_This documents an experimental, unreleased feature available in Guice SVN
only_
+
+Occasionally it's necessary to bind a type to an arbitrary constructor.
This comes up when the `...@inject` annotation cannot be applied to the target
constructor: either because it is a third party class, or because
_multiple_ constructors that participate in dependency injection.
[ProvidesMethods @Provides methods] provide the best solution to this
problem! By calling your target constructor explicitly, you don't need
reflection and its associated pitfalls. But there are limitations of that
approach: manually constructed instances do not participate in [AOP AOP].
+
+To address this, Guice has `toConstructor()` bindings. They require you to
reflectively select your target constructor and handle the exception if
that constructor cannot be found:
+{{{
+public class BillingModule extends AbstractModule {
+ @Override
+ protected void configure() {
+ try {
+ bind(TransactionLog.class).toConstructor(
+
DatabaseTransactionLog.class.getConstructor(DatabaseConnection.class));
+ } catch (NoSuchMethodException e) {
+ addError(e);
+ }
+ }
+}
+}}}
+In this example, the `DatabaseTransactionLog` must have a constructor that
takes a single `DatabaseConnection` parameter. That constructor does not
need an `...@inject` annotation. Guice will invoke that constructor to satisfy
the binding.
+
+Each `toConstructor()` binding is scoped independently. If you create
multiple singleton bindings that target the same constructor, each binding
yields its own instance.
\ No newline at end of file
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"google-guice-dev" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/google-guice-dev?hl=en
-~----------~----~----~----~------~----~------~--~---