0
# Core Dependency Injection
1
2
Essential classes for creating injectors, configuring modules, and performing dependency injection. This is the primary API that most Guice applications will use.
3
4
## Capabilities
5
6
### Guice Factory Class
7
8
The main entry point for creating Injector instances from Module configurations.
9
10
```java { .api }
11
/**
12
* The entry point to the Guice framework. Creates Injectors from Modules.
13
*/
14
public final class Guice {
15
/**
16
* Creates an injector for the given set of modules in DEVELOPMENT stage.
17
* @param modules Configuration modules
18
* @return New Injector instance
19
* @throws CreationException if one or more errors occur during injector construction
20
*/
21
public static Injector createInjector(Module... modules);
22
23
/**
24
* Creates an injector for the given set of modules in DEVELOPMENT stage.
25
* @param modules Configuration modules as Iterable
26
* @return New Injector instance
27
* @throws CreationException if one or more errors occur during injector creation
28
*/
29
public static Injector createInjector(Iterable<? extends Module> modules);
30
31
/**
32
* Creates an injector for the given set of modules in a specific stage.
33
* @param stage Development stage (DEVELOPMENT, PRODUCTION, TOOL)
34
* @param modules Configuration modules
35
* @return New Injector instance
36
* @throws CreationException if one or more errors occur during injector creation
37
*/
38
public static Injector createInjector(Stage stage, Module... modules);
39
40
/**
41
* Creates an injector for the given set of modules in a specific stage.
42
* @param stage Development stage (DEVELOPMENT, PRODUCTION, TOOL)
43
* @param modules Configuration modules as Iterable
44
* @return New Injector instance
45
* @throws CreationException if one or more errors occur during injector construction
46
*/
47
public static Injector createInjector(Stage stage, Iterable<? extends Module> modules);
48
}
49
```
50
51
**Usage Examples:**
52
53
```java
54
import com.google.inject.*;
55
56
// Simple injector creation
57
Injector injector = Guice.createInjector(new MyModule());
58
59
// Multiple modules
60
Injector injector = Guice.createInjector(
61
new DatabaseModule(),
62
new ServiceModule(),
63
new WebModule()
64
);
65
66
// Production stage for optimized performance
67
Injector injector = Guice.createInjector(
68
Stage.PRODUCTION,
69
new MyModule()
70
);
71
```
72
73
### Injector Interface
74
75
The core dependency injection interface that builds object graphs and provides instances.
76
77
```java { .api }
78
/**
79
* Builds the graphs of objects that make up your application. The injector tracks
80
* dependencies for each type and uses bindings to inject them.
81
*/
82
public interface Injector {
83
/**
84
* Returns the instance of the given type.
85
* @param type Class to get instance of
86
* @return Instance of the specified type
87
* @throws ConfigurationException if binding is misconfigured
88
* @throws ProvisionException if instance could not be provided
89
*/
90
<T> T getInstance(Class<T> type);
91
92
/**
93
* Returns the instance bound to the given key.
94
* @param key Key identifying the binding
95
* @return Instance bound to the key
96
* @throws ConfigurationException if binding is misconfigured
97
* @throws ProvisionException if instance could not be provided
98
*/
99
<T> T getInstance(Key<T> key);
100
101
/**
102
* Returns the provider for the given type.
103
* @param type Class to get provider for
104
* @return Provider that supplies instances of the type
105
*/
106
<T> Provider<T> getProvider(Class<T> type);
107
108
/**
109
* Returns the provider bound to the given key.
110
* @param key Key identifying the binding
111
* @return Provider bound to the key
112
*/
113
<T> Provider<T> getProvider(Key<T> key);
114
115
/**
116
* Injects dependencies into the fields and methods of an existing object.
117
* @param instance Object to inject dependencies into
118
*/
119
void injectMembers(Object instance);
120
121
/**
122
* Returns a members injector for the given type.
123
* @param type Type to create members injector for
124
* @return MembersInjector for the type
125
*/
126
<T> MembersInjector<T> getMembersInjector(Class<T> type);
127
128
/**
129
* Returns a members injector for the given type literal.
130
* @param typeLiteral type to get members injector for
131
* @return MembersInjector for the type
132
* @since 2.0
133
*/
134
<T> MembersInjector<T> getMembersInjector(TypeLiteral<T> typeLiteral);
135
136
/**
137
* Returns a map of all explicit bindings.
138
* @return Map of Key to Binding for all explicit bindings
139
*/
140
Map<Key<?>, Binding<?>> getBindings();
141
142
/**
143
* Returns a snapshot of this injector's bindings, both explicit and just-in-time.
144
* The returned map is immutable; it contains only the bindings that were
145
* present when getAllBindings() was invoked.
146
* @return Map of all bindings (explicit and just-in-time)
147
* @since 3.0
148
*/
149
Map<Key<?>, Binding<?>> getAllBindings();
150
151
/**
152
* Returns the binding for the given injection key.
153
* @param key Key to get binding for
154
* @return Binding for the key
155
* @throws ConfigurationException if this injector cannot find or create the binding
156
*/
157
<T> Binding<T> getBinding(Key<T> key);
158
159
/**
160
* Returns the binding for the given type.
161
* @param type Class to get binding for
162
* @return Binding for the type
163
* @throws ConfigurationException if this injector cannot find or create the binding
164
* @since 2.0
165
*/
166
<T> Binding<T> getBinding(Class<T> type);
167
168
/**
169
* Returns the binding if it already exists, or null if it does not exist.
170
* Unlike getBinding(Key), this does not attempt to create just-in-time bindings.
171
* @param key Key to check for existing binding
172
* @return Existing binding or null
173
* @since 3.0
174
*/
175
<T> Binding<T> getExistingBinding(Key<T> key);
176
177
/**
178
* Returns all explicit bindings for the given type.
179
* @param type Type to find bindings for
180
* @return List of bindings for the type
181
*/
182
<T> List<Binding<T>> findBindingsByType(TypeLiteral<T> type);
183
184
/**
185
* Creates a child injector that inherits bindings from this injector.
186
* @param modules Additional modules for the child injector
187
* @return Child injector with inherited and additional bindings
188
*/
189
Injector createChildInjector(Iterable<? extends Module> modules);
190
191
/**
192
* Creates a child injector that inherits bindings from this injector.
193
* @param modules Additional modules for the child injector
194
* @return Child injector with inherited and additional bindings
195
*/
196
Injector createChildInjector(Module... modules);
197
198
/**
199
* Returns the parent injector, or null if this is a top-level injector.
200
* @return Parent injector or null
201
* @since 2.0
202
*/
203
Injector getParent();
204
205
/**
206
* Returns a map containing all scopes in the injector.
207
* @return Map of scope annotation to scope instance
208
* @since 3.0
209
*/
210
Map<Class<? extends Annotation>, Scope> getScopeBindings();
211
212
/**
213
* Returns a set containing all type converter bindings in the injector.
214
* @return Set of type converter bindings
215
* @since 3.0
216
*/
217
Set<TypeConverterBinding> getTypeConverterBindings();
218
}
219
```
220
221
**Usage Examples:**
222
223
```java
224
// Get instances directly
225
DatabaseService dbService = injector.getInstance(DatabaseService.class);
226
UserService userService = injector.getInstance(UserService.class);
227
228
// Get instances with binding annotations
229
Cache primaryCache = injector.getInstance(Key.get(Cache.class, Names.named("primary")));
230
Cache secondaryCache = injector.getInstance(Key.get(Cache.class, Names.named("secondary")));
231
232
// Get providers for lazy initialization
233
Provider<ExpensiveService> expensiveProvider = injector.getProvider(ExpensiveService.class);
234
ExpensiveService service = expensiveProvider.get(); // Created only when needed
235
236
// Inject into existing objects
237
MyController controller = new MyController();
238
injector.injectMembers(controller); // Injects @Inject fields and methods
239
240
// Create child injectors for scoped contexts
241
Injector requestInjector = injector.createChildInjector(new RequestModule());
242
```
243
244
### MembersInjector Interface
245
246
Injects dependencies into fields and methods of existing instances.
247
248
```java { .api }
249
/**
250
* Injects dependencies into the fields and methods of existing instances.
251
* @param <T> Type of object to inject into
252
*/
253
public interface MembersInjector<T> {
254
/**
255
* Injects dependencies into the fields and methods of the given instance.
256
* @param instance Object to inject dependencies into
257
*/
258
void injectMembers(T instance);
259
}
260
```
261
262
### Stage Enumeration
263
264
Defines the different stages of injector creation affecting validation and performance.
265
266
```java { .api }
267
/**
268
* Enumeration of injector development stages.
269
*/
270
public enum Stage {
271
/**
272
* Development stage with extensive error checking and validation.
273
* Recommended for development and testing.
274
*/
275
DEVELOPMENT,
276
277
/**
278
* Production stage with optimized performance and minimal validation.
279
* Recommended for production deployments.
280
*/
281
PRODUCTION,
282
283
/**
284
* Tool stage for static analysis and IDE integration.
285
* Used by development tools and code generators.
286
*/
287
TOOL
288
}
289
```
290
291
## Exception Types
292
293
### CreationException
294
295
Thrown when injector creation fails due to configuration errors.
296
297
```java { .api }
298
/**
299
* Thrown when injector creation fails due to configuration problems.
300
*/
301
public class CreationException extends RuntimeException {
302
/**
303
* Returns the configuration messages describing the problems.
304
* @return Collection of error messages
305
*/
306
public Collection<Message> getErrorMessages();
307
}
308
```
309
310
### ProvisionException
311
312
Thrown when instance provision fails during injection.
313
314
```java { .api }
315
/**
316
* Thrown when instance provision fails.
317
*/
318
public class ProvisionException extends RuntimeException {
319
/**
320
* Returns the error messages describing the provision problems.
321
* @return Collection of error messages
322
*/
323
public Collection<Message> getErrorMessages();
324
}
325
```
326
327
### ConfigurationException
328
329
Thrown when bindings are misconfigured.
330
331
```java { .api }
332
/**
333
* Thrown when the injector encounters configuration problems.
334
*/
335
public class ConfigurationException extends RuntimeException {
336
/**
337
* Returns the configuration error messages.
338
* @return Collection of error messages
339
*/
340
public Collection<Message> getErrorMessages();
341
}
342
```
343
344
### OutOfScopeException
345
346
Thrown from Provider.get() when attempting to access a scoped object while the scope is not active.
347
348
```java { .api }
349
/**
350
* Thrown from Provider.get() when an attempt is made to access a scoped object
351
* while the scope in question is not currently active.
352
* @since 2.0
353
*/
354
public final class OutOfScopeException extends RuntimeException {
355
public OutOfScopeException(String message);
356
public OutOfScopeException(String message, Throwable cause);
357
public OutOfScopeException(Throwable cause);
358
}
359
```