Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'd like to complement Marcin's response, by adding that you don't have to limit yourself to using <code>toInstance()</code> or provider methods in such a situation.</p> <p>The following will work just as well:</p> <pre><code>bind(Person.class).annotatedWith(Driver.class).to(MartyMcFly.class).in(Singleton.class); bind(Person.class).annotatedWith(Inventor.class).to(DocBrown.class).in(Singleton.class); </code></pre> <p>[...]</p> <pre><code>@Inject public BackToTheFuture(@Driver Person marty, @Inventor Person doc) { ... } </code></pre> <p>Guice will inject the dependencies as usual when instantiating the MartyMcFly and DocBrown classes.</p> <hr> <p>Note that it also works when you want to bind multiple singletons of the <strong>same type</strong>:</p> <pre><code>bind(Person.class).annotatedWith(Driver.class).to(Person.class).in(Singleton.class); bind(Person.class).annotatedWith(Inventor.class).to(Person.class).in(Singleton.class); </code></pre> <p>For this to work, you must make sure that <code>Person</code> is not bound in the Singleton scope, either explicitely in the Guice module, or with the <code>@Singleton</code> annotation. More details in <a href="https://gist.github.com/1156593" rel="nofollow noreferrer">this Gist</a>.</p> <p>Edit: The sample code I give as an example comes from a <a href="https://github.com/google/guice/blob/e7bef34ef6379735e2a58df1b23f351bb7e30e44/extensions/grapher/test/com/google/inject/grapher/demo/BackToTheFutureModule.java" rel="nofollow noreferrer">Guice Grapher Test</a>. Looking at the Guice tests is a great way to better understand how to use the API (which also applies to every project with good unit tests).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload