0
# CDI and Dependency Injection
1
2
Quarkus uses ArC, a build-time optimized CDI container that provides dependency injection, context management, and lifecycle handling with full native image support.
3
4
## ArC Container Access
5
6
### Arc Main Class
7
8
```java { .api }
9
public final class Arc {
10
public static ArcContainer initialize();
11
public static ArcContainer initialize(ArcInitConfig config);
12
public static void setExecutor(ExecutorService executor);
13
public static ArcContainer container();
14
public static void shutdown();
15
}
16
```
17
18
Main access point to the ArC CDI container. Use `container()` to access container services programmatically.
19
20
**Usage Example:**
21
```java
22
import io.quarkus.arc.Arc;
23
import io.quarkus.arc.InstanceHandle;
24
25
// Get a bean instance programmatically
26
InstanceHandle<MyService> handle = Arc.container().instance(MyService.class);
27
MyService service = handle.get();
28
29
// Use the service
30
service.doSomething();
31
32
// Clean up when done
33
handle.destroy();
34
```
35
36
### ArcContainer Interface
37
38
```java { .api }
39
public interface ArcContainer {
40
// Bean instance access
41
<T> InstanceHandle<T> instance(Class<T> type, Annotation... qualifiers);
42
<T> InstanceHandle<T> instance(TypeLiteral<T> type, Annotation... qualifiers);
43
<X> InstanceHandle<X> instance(Type type, Annotation... qualifiers);
44
<T> InstanceHandle<T> instance(String name);
45
<T> InstanceHandle<T> instance(InjectableBean<T> bean);
46
47
// Programmatic selection
48
<T> InjectableInstance<T> select(Class<T> type, Annotation... qualifiers);
49
<T> InjectableInstance<T> select(TypeLiteral<T> type, Annotation... qualifiers);
50
51
// Bean listing and suppliers
52
<T> List<InstanceHandle<T>> listAll(Class<T> type, Annotation... qualifiers);
53
<T> List<InstanceHandle<T>> listAll(TypeLiteral<T> type, Annotation... qualifiers);
54
<X> List<InstanceHandle<X>> listAll(Type type, Annotation... qualifiers);
55
<T> Supplier<InstanceHandle<T>> beanInstanceSupplier(Class<T> type, Annotation... qualifiers);
56
57
// Bean access
58
<T> InjectableBean<T> bean(String beanIdentifier);
59
InjectableBean<?> namedBean(String name);
60
61
// Context management
62
InjectableContext getActiveContext(Class<? extends Annotation> scopeType);
63
List<InjectableContext> getContexts(Class<? extends Annotation> scopeType);
64
Set<Class<? extends Annotation>> getScopes();
65
ManagedContext requestContext();
66
ManagedContext sessionContext();
67
68
// Container state and services
69
boolean isRunning();
70
BeanManager beanManager();
71
ExecutorService getExecutorService();
72
CurrentContextFactory getCurrentContextFactory();
73
boolean strictCompatibility();
74
75
// Event observers
76
<T> List<InjectableObserverMethod<? super T>> resolveObserverMethods(Type eventType, Annotation... eventQualifiers);
77
}
78
```
79
80
The main container interface providing bean access and lifecycle management.
81
82
### InstanceHandle Interface
83
84
```java { .api }
85
public interface InstanceHandle<T> extends AutoCloseable, Instance.Handle<T> {
86
T get();
87
default boolean isAvailable();
88
default T orElse(T other);
89
default void destroy();
90
default InjectableBean<T> getBean();
91
@Override
92
default void close();
93
}
94
```
95
96
Handle for managed bean instances with automatic lifecycle management.
97
98
### InjectableInstance Interface
99
100
```java { .api }
101
public interface InjectableInstance<T> extends Instance<T> {
102
@Override
103
InjectableInstance<T> select(Annotation... qualifiers);
104
@Override
105
<U extends T> InjectableInstance<U> select(Class<U> subtype, Annotation... qualifiers);
106
@Override
107
<U extends T> InjectableInstance<U> select(TypeLiteral<U> subtype, Annotation... qualifiers);
108
109
@Override
110
InstanceHandle<T> getHandle();
111
@Override
112
Iterable<InstanceHandle<T>> handles();
113
@Override
114
default Stream<InstanceHandle<T>> handlesStream();
115
116
void clearCache();
117
@Override
118
Iterator<T> iterator();
119
default T orElse(T other);
120
default T orNull();
121
default T getActive();
122
default List<T> listActive();
123
}
124
```
125
126
CDI `Instance` wrapper providing programmatic bean access with ArC-specific enhancements.
127
128
## Standard CDI Annotations
129
130
### Scope Annotations
131
132
```java { .api }
133
@Target(ElementType.TYPE)
134
@Retention(RetentionPolicy.RUNTIME)
135
@Scope
136
public @interface ApplicationScoped {
137
}
138
```
139
140
Application-scoped beans (singleton per application).
141
142
```java { .api }
143
@Target(ElementType.TYPE)
144
@Retention(RetentionPolicy.RUNTIME)
145
@Scope
146
public @interface RequestScoped {
147
}
148
```
149
150
Request-scoped beans (one instance per request).
151
152
```java { .api }
153
@Target(ElementType.TYPE)
154
@Retention(RetentionPolicy.RUNTIME)
155
@Scope
156
public @interface SessionScoped {
157
}
158
```
159
160
Session-scoped beans (one instance per HTTP session).
161
162
```java { .api }
163
@Target(ElementType.TYPE)
164
@Retention(RetentionPolicy.RUNTIME)
165
@Scope
166
public @interface Singleton {
167
}
168
```
169
170
Singleton-scoped beans (eager instantiation).
171
172
**Usage Example:**
173
```java
174
@ApplicationScoped
175
public class UserService {
176
177
@Inject
178
UserRepository repository;
179
180
public User findById(Long id) {
181
return repository.findById(id);
182
}
183
}
184
```
185
186
### Injection Annotations
187
188
```java { .api }
189
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
190
@Retention(RetentionPolicy.RUNTIME)
191
public @interface Inject {
192
}
193
```
194
195
Standard CDI injection annotation.
196
197
```java { .api }
198
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
199
@Retention(RetentionPolicy.RUNTIME)
200
public @interface Named {
201
String value() default "";
202
}
203
```
204
205
Named qualifier for disambiguation.
206
207
## ArC-Specific Extensions
208
209
### Bean Configuration Annotations
210
211
```java { .api }
212
@Target(ElementType.TYPE)
213
@Retention(RetentionPolicy.RUNTIME)
214
public @interface DefaultBean {
215
}
216
```
217
218
Marks beans as default implementations that can be overridden by other beans.
219
220
**Usage Example:**
221
```java
222
@DefaultBean
223
@ApplicationScoped
224
public class DefaultEmailService implements EmailService {
225
// Default implementation
226
}
227
228
@ApplicationScoped // This will override the default
229
public class CustomEmailService implements EmailService {
230
// Custom implementation
231
}
232
```
233
234
```java { .api }
235
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
236
@Retention(RetentionPolicy.RUNTIME)
237
public @interface Unremovable {
238
}
239
```
240
241
Prevents bean removal during build-time optimization.
242
243
```java { .api }
244
@Target({ElementType.FIELD, ElementType.PARAMETER})
245
@Retention(RetentionPolicy.RUNTIME)
246
@Qualifier
247
public @interface All {
248
}
249
```
250
251
Qualifier for injecting all instances of a particular type.
252
253
**Usage Example:**
254
```java
255
@ApplicationScoped
256
public class NotificationService {
257
258
@Inject
259
@All
260
List<NotificationHandler> handlers; // Injects all NotificationHandler implementations
261
262
public void notify(String message) {
263
handlers.forEach(handler -> handler.handle(message));
264
}
265
}
266
```
267
268
### Producer Configuration
269
270
```java { .api }
271
@Target(ElementType.METHOD)
272
@Retention(RetentionPolicy.RUNTIME)
273
public @interface VetoedProducer {
274
}
275
```
276
277
Excludes producer methods from CDI processing.
278
279
## Programmatic Bean Management
280
281
### BeanCreator
282
283
```java { .api }
284
public abstract class BeanCreator<T> {
285
public static <T> BeanCreator<T> create(Class<T> beanClass);
286
public BeanCreator<T> scope(Class<? extends Annotation> scope);
287
public BeanCreator<T> addQualifier(Annotation qualifier);
288
public BeanCreator<T> creator(CreationalContext<T> creationalContext);
289
public void done();
290
}
291
```
292
293
Programmatic API for creating beans at runtime.
294
295
### BeanDestroyer
296
297
```java { .api }
298
public interface BeanDestroyer<T> {
299
void destroy(T instance, CreationalContext<T> creationalContext);
300
}
301
```
302
303
Interface for custom bean destruction logic.
304
305
## Context Management
306
307
### ManagedContext
308
309
```java { .api }
310
public interface ManagedContext extends InjectableContext {
311
void activate();
312
void deactivate();
313
void terminate();
314
boolean isActive();
315
}
316
```
317
318
Interface for programmatically managed contexts.
319
320
**Usage Example:**
321
```java
322
@ApplicationScoped
323
public class RequestContextService {
324
325
@Inject
326
ManagedContext requestContext;
327
328
public void executeInRequestContext(Runnable task) {
329
requestContext.activate();
330
try {
331
task.run();
332
} finally {
333
requestContext.terminate();
334
}
335
}
336
}
337
```
338
339
### InjectableContext Interface
340
341
```java { .api }
342
public interface InjectableContext extends Context {
343
void destroy();
344
void destroy(Contextual<?> contextual);
345
ContextState getState();
346
}
347
```
348
349
Enhanced context interface with destruction capabilities.
350
351
### CurrentContext
352
353
```java { .api }
354
public class CurrentContext {
355
public static boolean isActive(Class<? extends Annotation> scopeType);
356
public static <T> T get(Class<T> beanClass);
357
public static <T> T get(Class<T> beanClass, Annotation... qualifiers);
358
}
359
```
360
361
Utility class for accessing current context state.
362
363
## Event System
364
365
### Event Production and Observation
366
367
```java { .api }
368
@Target({ElementType.PARAMETER, ElementType.FIELD})
369
@Retention(RetentionPolicy.RUNTIME)
370
public @interface Observes {
371
Reception notifyObserver() default Reception.ALWAYS;
372
TransactionPhase during() default TransactionPhase.IN_PROGRESS;
373
}
374
```
375
376
Standard CDI event observation annotation.
377
378
```java { .api }
379
public interface Event<T> {
380
void fire(T event);
381
<U extends T> void fireAsync(U event);
382
Event<T> select(Annotation... qualifiers);
383
}
384
```
385
386
Interface for firing CDI events.
387
388
**Usage Example:**
389
```java
390
@ApplicationScoped
391
public class OrderService {
392
393
@Inject
394
Event<OrderPlaced> orderEvent;
395
396
public void placeOrder(Order order) {
397
// Process order
398
orderEvent.fire(new OrderPlaced(order));
399
}
400
}
401
402
@ApplicationScoped
403
public class OrderEventHandler {
404
405
void onOrderPlaced(@Observes OrderPlaced event) {
406
System.out.println("Order placed: " + event.getOrder().getId());
407
}
408
}
409
```
410
411
## Interceptors and Decorators
412
413
### Interceptor Annotations
414
415
```java { .api }
416
@Target(ElementType.TYPE)
417
@Retention(RetentionPolicy.RUNTIME)
418
@InterceptorBinding
419
public @interface Transactional {
420
TxType value() default TxType.REQUIRED;
421
Class[] rollbackOn() default {};
422
Class[] dontRollbackOn() default {};
423
}
424
```
425
426
Transaction interceptor binding (example of interceptor usage).
427
428
### ArC Priority Constants
429
430
```java { .api }
431
public final class InvocationContextImpl {
432
public static final int PLATFORM_BEFORE = 0;
433
public static final int LIBRARY_BEFORE = 1000;
434
public static final int APPLICATION = 2000;
435
public static final int LIBRARY_AFTER = 3000;
436
public static final int PLATFORM_AFTER = 4000;
437
}
438
```
439
440
Priority constants for ordering interceptors and observers.
441
442
## Configuration Integration
443
444
### ConfigProperties Integration
445
446
```java { .api }
447
@Target(ElementType.TYPE)
448
@Retention(RetentionPolicy.RUNTIME)
449
public @interface ConfigProperties {
450
String prefix() default "";
451
NamingStrategy namingStrategy() default NamingStrategy.KEBAB_CASE;
452
}
453
```
454
455
Integration between CDI and MicroProfile Config for configuration properties binding.
456
457
**Usage Example:**
458
```java
459
@ConfigProperties(prefix = "app.database")
460
@ApplicationScoped
461
public class DatabaseConfig {
462
public String host;
463
public int port;
464
public String username;
465
public String password;
466
}
467
```