My favorites | Sign in
Google
                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/**
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.inject.multibindings;

import com.google.inject.AbstractModule;
import com.google.inject.Binder;
import com.google.inject.Binding;
import com.google.inject.ConfigurationException;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import com.google.inject.binder.LinkedBindingBuilder;
import com.google.inject.internal.Errors;
import com.google.inject.internal.ImmutableList;
import com.google.inject.internal.ImmutableSet;
import com.google.inject.internal.Lists;
import static com.google.inject.name.Names.named;
import com.google.inject.spi.Dependency;
import com.google.inject.spi.HasDependencies;
import com.google.inject.spi.Message;
import com.google.inject.util.Types;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
* An API to bind multiple values separately, only to later inject them as a
* complete collection. Multibinder is intended for use in your application's
* module:
* <pre><code>
* public class SnacksModule extends AbstractModule {
* protected void configure() {
* Multibinder&lt;Snack&gt; multibinder
* = Multibinder.newSetBinder(binder(), Snack.class);
* multibinder.addBinding().toInstance(new Twix());
* multibinder.addBinding().toProvider(SnickersProvider.class);
* multibinder.addBinding().to(Skittles.class);
* }
* }</code></pre>
*
* <p>With this binding, a {@link Set}{@code <Snack>} can now be injected:
* <pre><code>
* class SnackMachine {
* {@literal @}Inject
* public SnackMachine(Set&lt;Snack&gt; snacks) { ... }
* }</code></pre>
*
* <p>Create multibindings from different modules is supported. For example, it
* is okay to have both {@code CandyModule} and {@code ChipsModule} to both
* create their own {@code Multibinder<Snack>}, and to each contribute bindings
* to the set of snacks. When that set is injected, it will contain elements
* from both modules.
*
* <p>Elements are resolved at set injection time. If an element is bound to a
* provider, that provider's get method will be called each time the set is
* injected (unless the binding is also scoped).
*
* <p>Annotations are be used to create different sets of the same element
* type. Each distinct annotation gets its own independent collection of
* elements.
*
* <p><strong>Elements must be distinct.</strong> If multiple bound elements
* have the same value, set injection will fail.
*
* <p><strong>Elements must be non-null.</strong> If any set element is null,
* set injection will fail.
*
* @author jessewilson@google.com (Jesse Wilson)
*/
public abstract class Multibinder<T> {
private Multibinder() {}

/**
* Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is
* itself bound with no binding annotation.
*/
public static <T> Multibinder<T> newSetBinder(Binder binder, TypeLiteral<T> type) {
binder = binder.skipSources(RealMultibinder.class, Multibinder.class);
RealMultibinder<T> result = new RealMultibinder<T>(binder, type, "",
Key.get(Multibinder.<T>setOf(type)));
binder.install(result);
return result;
}

/**
* Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is
* itself bound with no binding annotation.
*/
public static <T> Multibinder<T> newSetBinder(Binder binder, Class<T> type) {
return newSetBinder(binder, TypeLiteral.get(type));
}

/**
* Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is
* itself bound with {@code annotation}.
*/
public static <T> Multibinder<T> newSetBinder(
Binder binder, TypeLiteral<T> type, Annotation annotation) {
binder = binder.skipSources(RealMultibinder.class, Multibinder.class);
RealMultibinder<T> result = new RealMultibinder<T>(binder, type, annotation.toString(),
Key.get(Multibinder.<T>setOf(type), annotation));
binder.install(result);
return result;
}

/**
* Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is
* itself bound with {@code annotation}.
*/
public static <T> Multibinder<T> newSetBinder(
Binder binder, Class<T> type, Annotation annotation) {
return newSetBinder(binder, TypeLiteral.get(type), annotation);
}

/**
* Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is
* itself bound with {@code annotationType}.
*/
public static <T> Multibinder<T> newSetBinder(Binder binder, TypeLiteral<T> type,
Class<? extends Annotation> annotationType) {
binder = binder.skipSources(RealMultibinder.class, Multibinder.class);
RealMultibinder<T> result = new RealMultibinder<T>(binder, type, "@" + annotationType.getName(),
Key.get(Multibinder.<T>setOf(type), annotationType));
binder.install(result);
return result;
}

/**
* Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is
* itself bound with {@code annotationType}.
*/
public static <T> Multibinder<T> newSetBinder(Binder binder, Class<T> type,
Class<? extends Annotation> annotationType) {
return newSetBinder(binder, TypeLiteral.get(type), annotationType);
}

@SuppressWarnings("unchecked") // wrapping a T in a Set safely returns a Set<T>
static <T> TypeLiteral<Set<T>> setOf(TypeLiteral<T> elementType) {
Type type = Types.setOf(elementType.getType());
return (TypeLiteral<Set<T>>) TypeLiteral.get(type);
}

/**
* Configures the bound set to silently discard duplicate elements. When multiple equal values are
* bound, the one that gets included is arbitrary. When multiple modules contribute elements to
* the set, this configuration option impacts all of them.
*
* @return this multibinder
*/
public abstract Multibinder<T> permitDuplicates();

/**
* Returns a binding builder used to add a new element in the set. Each
* bound element must have a distinct value. Bound providers will be
* evaluated each time the set is injected.
*
* <p>It is an error to call this method without also calling one of the
* {@code to} methods on the returned binding builder.
*
* <p>Scoping elements independently is supported. Use the {@code in} method
* to specify a binding scope.
*/
public abstract LinkedBindingBuilder<T> addBinding();

/**
* The actual multibinder plays several roles:
*
* <p>As a Multibinder, it acts as a factory for LinkedBindingBuilders for
* each of the set's elements. Each binding is given an annotation that
* identifies it as a part of this set.
*
* <p>As a Module, it installs the binding to the set itself. As a module,
* this implements equals() and hashcode() in order to trick Guice into
* executing its configure() method only once. That makes it so that
* multiple multibinders can be created for the same target collection, but
* only one is bound. Since the list of bindings is retrieved from the
* injector itself (and not the multibinder), each multibinder has access to
* all contributions from all multibinders.
*
* <p>As a Provider, this constructs the set instances.
*
* <p>We use a subclass to hide 'implements Module, Provider' from the public
* API.
*/
static final class RealMultibinder<T> extends Multibinder<T>
implements Module, Provider<Set<T>>, HasDependencies {

private final TypeLiteral<T> elementType;
private final String setName;
private final Key<Set<T>> setKey;
private final Key<Boolean> permitDuplicatesKey;

/* the target injector's binder. non-null until initialization, null afterwards */
private Binder binder;

/* a provider for each element in the set. null until initialization, non-null afterwards */
private List<Provider<T>> providers;
private Set<Dependency<?>> dependencies;

/** whether duplicates are allowed. Possibly configured by a different instance */
private boolean permitDuplicates;

private RealMultibinder(Binder binder, TypeLiteral<T> elementType,
String setName, Key<Set<T>> setKey) {
this.binder = checkNotNull(binder, "binder");
this.elementType = checkNotNull(elementType, "elementType");
this.setName = checkNotNull(setName, "setName");
this.setKey = checkNotNull(setKey, "setKey");
this.permitDuplicatesKey = Key.get(Boolean.class, named(toString() + " permits duplicates"));
}

@SuppressWarnings("unchecked")
public void configure(Binder binder) {
checkConfiguration(!isInitialized(), "Multibinder was already initialized");

binder.bind(setKey).toProvider(this);
}

@Override
public Multibinder<T> permitDuplicates() {
binder.install(new PermitDuplicatesModule(permitDuplicatesKey));
return this;
}

@Override public LinkedBindingBuilder<T> addBinding() {
checkConfiguration(!isInitialized(), "Multibinder was already initialized");

return binder.bind(Key.get(elementType, new RealElement(setName)));
}

/**
* Invoked by Guice at Injector-creation time to prepare providers for each
* element in this set. At this time the set's size is known, but its
* contents are only evaluated when get() is invoked.
*/
@Inject void initialize(Injector injector) {
providers = Lists.newArrayList();
List<Dependency<?>> dependencies = Lists.newArrayList();
for (Binding<?> entry : injector.findBindingsByType(elementType)) {

if (keyMatches(entry.getKey())) {
@SuppressWarnings("unchecked") // protected by findBindingsByType()
Binding<T> binding = (Binding<T>) entry;
providers.add(binding.getProvider());
dependencies.add(Dependency.get(binding.getKey()));
}
}

this.dependencies = ImmutableSet.copyOf(dependencies);
this.permitDuplicates = permitsDuplicates(injector);
this.binder = null;
}

boolean permitsDuplicates(Injector injector) {
return injector.getBindings().containsKey(permitDuplicatesKey);
}

private boolean keyMatches(Key<?> key) {
return key.getTypeLiteral().equals(elementType)
&& key.getAnnotation() instanceof Element
&& ((Element) key.getAnnotation()).setName().equals(setName);
}

private boolean isInitialized() {
return binder == null;
}

public Set<T> get() {
checkConfiguration(isInitialized(), "Multibinder is not initialized");

Set<T> result = new LinkedHashSet<T>();
for (Provider<T> provider : providers) {
final T newValue = provider.get();
checkConfiguration(newValue != null, "Set injection failed due to null element");
checkConfiguration(result.add(newValue) || permitDuplicates,
"Set injection failed due to duplicated element \"%s\"", newValue);
}
return Collections.unmodifiableSet(result);
}

String getSetName() {
return setName;
}

Key<Set<T>> getSetKey() {
return setKey;
}

public Set<Dependency<?>> getDependencies() {
return dependencies;
}

@Override public boolean equals(Object o) {
return o instanceof RealMultibinder
&& ((RealMultibinder<?>) o).setKey.equals(setKey);
}

@Override public int hashCode() {
return setKey.hashCode();
}

@Override public String toString() {
return new StringBuilder()
.append(setName)
.append(setName.length() > 0 ? " " : "")
.append("Multibinder<")
.append(elementType)
.append(">")
.toString();
}
}

/**
* We install the permit duplicates configuration as its own binding, all by itself. This way,
* if only one of a multibinder's users remember to call permitDuplicates(), they're still
* permitted.
*/
private static class PermitDuplicatesModule extends AbstractModule {
private final Key<Boolean> key;

PermitDuplicatesModule(Key<Boolean> key) {
this.key = key;
}

@Override
protected void configure() {
bind(key).toInstance(true);
}

@Override public boolean equals(Object o) {
return o instanceof PermitDuplicatesModule
&& ((PermitDuplicatesModule) o).key.equals(key);
}

@Override public int hashCode() {
return getClass().hashCode() ^ key.hashCode();
}
}

static void checkConfiguration(boolean condition, String format, Object... args) {
if (condition) {
return;
}

throw new ConfigurationException(ImmutableSet.of(new Message(Errors.format(format, args))));
}

static <T> T checkNotNull(T reference, String name) {
if (reference != null) {
return reference;
}

NullPointerException npe = new NullPointerException(name);
throw new ConfigurationException(ImmutableSet.of(
new Message(ImmutableList.of(), npe.toString(), npe)));
}
}
Show details Hide details

Change log

r1041 by netdpb on Jul 07 (5 days ago)   Diff
Added mutlimap support to MapBinder.
Go to: 
Sign in to write a code review

Older revisions

r1035 by limpbizkit on Jun 23, 2009   Diff
Fixin' a doc typo
r1034 by limpbizkit on Jun 22, 2009   Diff
New API:
Multibinder.permitDuplicates() and
MapBinder.permitDuplicates()

When a map binder is configured to
...
r859 by limpbizkit on Feb 20, 2009   Diff
Regrettably replacing jarjar'd Google
Collections with minimal copies of the
parts that we use.

The main benefit is a (significant)
...
All revisions of this file

File info

Size: 13797 bytes, 377 lines