0
# Dependency Injection
1
2
Play Framework's dependency injection system provides Guice-based dependency injection with fluent builder patterns for application configuration, module binding, and injector management. The system enables comprehensive IoC container management with flexible module composition and environment-specific configuration.
3
4
## Capabilities
5
6
### Application Builder
7
8
Comprehensive builder for Guice-backed Play applications with fluent configuration API.
9
10
```java { .api }
11
/**
12
* Builder for Guice-backed Play applications with comprehensive configuration
13
*/
14
public final class GuiceApplicationBuilder extends GuiceBuilder<GuiceApplicationBuilder, play.api.inject.guice.GuiceApplicationBuilder> {
15
/** Create new application builder */
16
public GuiceApplicationBuilder();
17
18
/** Set custom configuration loader function */
19
public GuiceApplicationBuilder loadConfig(Function<Environment, Configuration> load);
20
21
/** Set specific configuration */
22
public GuiceApplicationBuilder loadConfig(Configuration conf);
23
24
/** Set global settings (deprecated in newer versions) */
25
public GuiceApplicationBuilder global(GlobalSettings global);
26
27
/** Load GuiceableModule modules */
28
public GuiceApplicationBuilder load(GuiceableModule... modules);
29
30
/** Load Google Guice modules */
31
public GuiceApplicationBuilder load(com.google.inject.Module... modules);
32
33
/** Load Play API modules */
34
public GuiceApplicationBuilder load(play.api.inject.Module... modules);
35
36
/** Load Play API bindings */
37
public GuiceApplicationBuilder load(play.api.inject.Binding<?>... bindings);
38
39
/** Load modules using custom loader function */
40
public GuiceApplicationBuilder load(java.util.function.BiFunction<Environment, Configuration, List<GuiceableModule>> loader);
41
42
/** Build the configured application */
43
public Application build();
44
}
45
46
/**
47
* Default builder for creating Guice-backed Injectors without Application context
48
*/
49
public final class GuiceInjectorBuilder extends GuiceBuilder<GuiceInjectorBuilder, play.api.inject.guice.GuiceInjectorBuilder> {
50
/** Create new injector builder */
51
public GuiceInjectorBuilder();
52
53
/** Build the configured injector */
54
public Injector build();
55
}
56
57
/**
58
* Base builder for Guice-backed Play components with common configuration
59
*/
60
public abstract class GuiceBuilder<Self, Delegate extends play.api.inject.guice.GuiceBuilder<Delegate>> {
61
/** Set the environment */
62
public final Self in(Environment env);
63
64
/** Set the environment path */
65
public final Self in(File path);
66
67
/** Set the environment mode */
68
public final Self in(Mode mode);
69
70
/** Set environment class loader */
71
public final Self in(ClassLoader classLoader);
72
73
/** Set configuration map */
74
public final Self configure(Map<String, Object> conf);
75
76
/** Set configuration key-value pair */
77
public final Self configure(String key, Object value);
78
79
/** Override bindings */
80
public final Self overrides(GuiceableModule... overrides);
81
}
82
```
83
84
**Usage Examples:**
85
86
```java
87
import play.inject.guice.GuiceApplicationBuilder;
88
import play.inject.guice.Guiceable;
89
import com.google.inject.AbstractModule;
90
91
// Basic application building
92
public class ApplicationLoader extends play.ApplicationLoader {
93
94
@Override
95
public Application load(Context context) {
96
return new GuiceApplicationBuilder()
97
.in(context.environment())
98
.loadConfig(context.initialConfiguration())
99
.build();
100
}
101
}
102
103
// Advanced configuration
104
public Application createApplication() {
105
return new GuiceApplicationBuilder()
106
.in(Environment.simple())
107
.configure("play.http.secret.key", "changeme")
108
.configure("db.default.driver", "org.h2.Driver")
109
.configure("db.default.url", "jdbc:h2:mem:play")
110
.bindings(new DatabaseModule())
111
.overrides(new TestModule())
112
.build();
113
}
114
```
115
116
### Application Loader
117
118
ApplicationLoader implementation using Guice for dependency injection bootstrapping.
119
120
```java { .api }
121
/**
122
* ApplicationLoader using Guice for bootstrapping Play applications
123
*/
124
public class GuiceApplicationLoader implements ApplicationLoader {
125
/** Create loader with default builder */
126
public GuiceApplicationLoader();
127
128
/** Create loader with custom initial builder */
129
public GuiceApplicationLoader(GuiceApplicationBuilder initialBuilder);
130
131
/** Load application with given context */
132
public Application load(ApplicationLoader.Context context);
133
134
/** Create builder for the given context */
135
public GuiceApplicationBuilder builder(ApplicationLoader.Context context);
136
137
/** Get override bindings for the context */
138
public GuiceableModule[] overrides(ApplicationLoader.Context context);
139
}
140
```
141
142
**Usage Examples:**
143
144
```java
145
// Custom application loader
146
public class CustomApplicationLoader extends GuiceApplicationLoader {
147
148
@Override
149
public GuiceApplicationBuilder builder(Context context) {
150
return super.builder(context)
151
.bindings(new MyCustomModule())
152
.configure("my.custom.setting", "value");
153
}
154
155
@Override
156
public GuiceableModule[] overrides(Context context) {
157
if (context.environment().isTest()) {
158
return new GuiceableModule[] {
159
Guiceable.modules(new TestModule())
160
};
161
}
162
return super.overrides(context);
163
}
164
}
165
```
166
167
### Guice Builder Base
168
169
Base builder class providing common functionality for Guice-backed components.
170
171
```java { .api }
172
/**
173
* Base builder for Guice-backed Play components with fluent configuration
174
*/
175
public abstract class GuiceBuilder<Self, Delegate> {
176
/** Set environment */
177
public Self in(Environment env);
178
179
/** Set environment path */
180
public Self in(File path);
181
182
/** Set environment mode */
183
public Self in(Mode mode);
184
185
/** Set class loader */
186
public Self in(ClassLoader classLoader);
187
188
/** Add configuration */
189
public Self configure(Configuration conf);
190
191
/** Add configuration from map */
192
public Self configure(Map<String, Object> conf);
193
194
/** Add single configuration setting */
195
public Self configure(String key, Object value);
196
197
/** Add binding modules */
198
public Self bindings(GuiceableModule... modules);
199
200
/** Override existing bindings */
201
public Self overrides(GuiceableModule... modules);
202
203
/** Disable specific module classes */
204
public Self disable(Class<?>... moduleClasses);
205
206
/** Create application module */
207
public Module applicationModule();
208
209
/** Create Guice injector */
210
public Injector injector();
211
}
212
```
213
214
### Injector Builder
215
216
Specialized builder for creating standalone Guice injectors without full Play application context.
217
218
```java { .api }
219
/**
220
* Builder for Guice-backed Injectors without full application context
221
*/
222
public class GuiceInjectorBuilder extends GuiceBuilder<GuiceInjectorBuilder, play.api.inject.guice.GuiceInjectorBuilder> {
223
/** Create new injector builder */
224
public GuiceInjectorBuilder();
225
226
/** Build the configured injector */
227
public Injector build();
228
}
229
```
230
231
**Usage Examples:**
232
233
```java
234
// Standalone injector for testing or utilities
235
public class ServiceFactory {
236
237
public static Injector createInjector() {
238
return new GuiceInjectorBuilder()
239
.configure("database.url", "jdbc:h2:mem:test")
240
.bindings(
241
Guiceable.modules(new DatabaseModule()),
242
Guiceable.modules(new ServiceModule())
243
)
244
.build();
245
}
246
247
public static <T> T getInstance(Class<T> clazz) {
248
return createInjector().getInstance(clazz);
249
}
250
}
251
252
// Usage in tests
253
@Test
254
public void testService() {
255
UserService userService = ServiceFactory.getInstance(UserService.class);
256
assertNotNull(userService);
257
}
258
```
259
260
### Module Utilities
261
262
Utilities for creating and managing GuiceableModules from various sources.
263
264
```java { .api }
265
/**
266
* Utilities for creating GuiceableModules from different sources
267
*/
268
public class Guiceable {
269
/** Create GuiceableModule from Guice modules */
270
public static GuiceableModule modules(com.google.inject.Module... modules);
271
272
/** Create GuiceableModule from Play modules */
273
public static GuiceableModule modules(play.api.inject.Module... modules);
274
275
/** Create GuiceableModule from bindings */
276
public static GuiceableModule bindings(play.api.inject.Binding... bindings);
277
278
/** Create GuiceableModule from arbitrary module object */
279
public static GuiceableModule module(Object module);
280
}
281
```
282
283
**Usage Examples:**
284
285
```java
286
import com.google.inject.AbstractModule;
287
import play.inject.guice.Guiceable;
288
289
// Standard Guice module
290
public class DatabaseModule extends AbstractModule {
291
@Override
292
protected void configure() {
293
bind(Database.class).to(H2Database.class);
294
bind(UserRepository.class).to(JpaUserRepository.class);
295
}
296
}
297
298
// Using Guiceable utilities
299
public Application buildApplication() {
300
return new GuiceApplicationBuilder()
301
.bindings(
302
Guiceable.modules(new DatabaseModule()),
303
Guiceable.modules(new ServiceModule()),
304
Guiceable.bindings(
305
bind(CacheApi.class).to(EhCacheApi.class)
306
)
307
)
308
.build();
309
}
310
```
311
312
### Built-in Module Support
313
314
Core module providing essential Play Framework bindings.
315
316
```java { .api }
317
/**
318
* Built-in dependency injection bindings for Play Framework
319
*/
320
public class BuiltInModule extends play.api.inject.Module {
321
/** Define core Play Framework bindings */
322
public Seq<Binding<?>> bindings(Environment environment, Configuration configuration);
323
}
324
```
325
326
### Configuration Provider
327
328
Java wrapper for Scala Configuration with Provider interface support.
329
330
```java { .api }
331
/**
332
* Provider for Java Configuration wrapper around Scala configuration
333
*/
334
public class ConfigurationProvider implements Provider<Configuration> {
335
/** Create provider with Scala configuration delegate */
336
public ConfigurationProvider(play.api.Configuration delegate);
337
338
/** Get Java Configuration instance */
339
public Configuration get();
340
}
341
```
342
343
### Application Lifecycle Management
344
345
Java wrapper for managing application lifecycle hooks and shutdown procedures.
346
347
```java { .api }
348
/**
349
* Java wrapper for Scala ApplicationLifecycle with stop hook support
350
*/
351
public class DelegateApplicationLifecycle implements ApplicationLifecycle {
352
/** Create wrapper for Scala ApplicationLifecycle */
353
public DelegateApplicationLifecycle(play.api.inject.ApplicationLifecycle delegate);
354
355
/** Add stop hook that executes on application shutdown */
356
public void addStopHook(Callable<F.Promise<Void>> hook);
357
}
358
```
359
360
**Usage Examples:**
361
362
```java
363
// Service with lifecycle management
364
@Singleton
365
public class DatabaseService {
366
367
@Inject
368
public DatabaseService(ApplicationLifecycle lifecycle) {
369
// Initialize database connection pool
370
initializeConnectionPool();
371
372
// Register cleanup on shutdown
373
lifecycle.addStopHook(() -> {
374
cleanupConnectionPool();
375
return F.Promise.pure(null);
376
});
377
}
378
379
private void initializeConnectionPool() {
380
// Database initialization
381
}
382
383
private void cleanupConnectionPool() {
384
// Cleanup resources
385
}
386
}
387
```
388
389
## Advanced Usage Patterns
390
391
### Custom Module Development
392
393
```java
394
// Custom module with conditional bindings
395
public class CustomModule extends AbstractModule {
396
private final Environment environment;
397
private final Configuration configuration;
398
399
public CustomModule(Environment env, Configuration config) {
400
this.environment = env;
401
this.configuration = config;
402
}
403
404
@Override
405
protected void configure() {
406
// Environment-specific bindings
407
if (environment.isProd()) {
408
bind(EmailService.class).to(SmtpEmailService.class);
409
bind(PaymentProcessor.class).to(StripePaymentProcessor.class);
410
} else {
411
bind(EmailService.class).to(MockEmailService.class);
412
bind(PaymentProcessor.class).to(MockPaymentProcessor.class);
413
}
414
415
// Configuration-driven bindings
416
String cacheProvider = configuration.getString("cache.provider");
417
if ("redis".equals(cacheProvider)) {
418
bind(CacheApi.class).to(RedisCacheApi.class);
419
} else {
420
bind(CacheApi.class).to(EhCacheApi.class);
421
}
422
423
// Singleton services
424
bind(UserService.class).in(Scopes.SINGLETON);
425
bind(AuditService.class).asEagerSingleton();
426
}
427
428
@Provides
429
@Singleton
430
public DatabaseConfig provideDatabaseConfig() {
431
return new DatabaseConfig(
432
configuration.getString("db.url"),
433
configuration.getString("db.username"),
434
configuration.getString("db.password")
435
);
436
}
437
}
438
```
439
440
### Testing Configuration
441
442
```java
443
// Test-specific application setup
444
public class TestApplicationBuilder {
445
446
public static Application buildTestApplication() {
447
return new GuiceApplicationBuilder()
448
.in(Environment.simple())
449
.configure("db.default.driver", "org.h2.Driver")
450
.configure("db.default.url", "jdbc:h2:mem:test")
451
.configure("play.evolutions.autoApply", "true")
452
.bindings(
453
Guiceable.modules(new TestDatabaseModule()),
454
Guiceable.modules(new MockServiceModule())
455
)
456
.overrides(
457
Guiceable.bindings(
458
bind(EmailService.class).to(MockEmailService.class)
459
)
460
)
461
.build();
462
}
463
}
464
465
// Test module
466
public class TestDatabaseModule extends AbstractModule {
467
@Override
468
protected void configure() {
469
bind(Database.class).to(H2InMemoryDatabase.class);
470
bind(UserRepository.class).to(InMemoryUserRepository.class);
471
}
472
}
473
```
474
475
### Multi-Environment Configuration
476
477
```java
478
// Environment-aware application loader
479
public class EnvironmentAwareLoader extends GuiceApplicationLoader {
480
481
@Override
482
public GuiceApplicationBuilder builder(Context context) {
483
GuiceApplicationBuilder builder = super.builder(context);
484
485
Environment env = context.environment();
486
487
if (env.isDev()) {
488
return configureDevelopment(builder);
489
} else if (env.isTest()) {
490
return configureTest(builder);
491
} else {
492
return configureProduction(builder);
493
}
494
}
495
496
private GuiceApplicationBuilder configureDevelopment(GuiceApplicationBuilder builder) {
497
return builder
498
.configure("play.http.secret.key", "dev-secret-change-me")
499
.configure("db.default.url", "jdbc:h2:mem:dev")
500
.bindings(Guiceable.modules(new DevModule()));
501
}
502
503
private GuiceApplicationBuilder configureTest(GuiceApplicationBuilder builder) {
504
return builder
505
.configure("db.default.url", "jdbc:h2:mem:test")
506
.bindings(Guiceable.modules(new TestModule()));
507
}
508
509
private GuiceApplicationBuilder configureProduction(GuiceApplicationBuilder builder) {
510
return builder
511
.bindings(Guiceable.modules(new ProdModule()))
512
.disable(DevModule.class, TestModule.class);
513
}
514
}
515
```
516
517
### Dynamic Module Loading
518
519
```java
520
// Dynamic module loading based on configuration
521
public class DynamicModuleLoader {
522
523
public static List<GuiceableModule> loadModules(Configuration config) {
524
List<GuiceableModule> modules = new ArrayList<>();
525
526
// Load modules specified in configuration
527
List<String> moduleNames = config.getStringList("play.modules.enabled");
528
529
for (String moduleName : moduleNames) {
530
try {
531
Class<?> moduleClass = Class.forName(moduleName);
532
Object moduleInstance = moduleClass.newInstance();
533
modules.add(Guiceable.module(moduleInstance));
534
} catch (Exception e) {
535
Logger.warn("Failed to load module: " + moduleName, e);
536
}
537
}
538
539
return modules;
540
}
541
}
542
543
// Usage in application loader
544
public class DynamicApplicationLoader extends GuiceApplicationLoader {
545
546
@Override
547
public GuiceApplicationBuilder builder(Context context) {
548
Configuration config = context.initialConfiguration();
549
List<GuiceableModule> dynamicModules = DynamicModuleLoader.loadModules(config);
550
551
return super.builder(context)
552
.bindings(dynamicModules.toArray(new GuiceableModule[0]));
553
}
554
}
555
```