0
# Application Context Management
1
2
The ApplicationContext is the main IoC container in Micronaut Inject, responsible for managing bean lifecycle, dependency resolution, and application configuration. It extends BeanContext with additional capabilities for application bootstrapping and environment management.
3
4
## Core Interfaces
5
6
### ApplicationContext
7
8
The primary interface for the Micronaut IoC container.
9
10
```java { .api }
11
public interface ApplicationContext extends BeanContext, LifeCycle<ApplicationContext> {
12
static ApplicationContext run();
13
static ApplicationContext run(Class<?> mainClass, String... args);
14
static ApplicationContext run(String... args);
15
static ApplicationContextBuilder builder();
16
static ApplicationContextBuilder builder(Class<?> mainClass, String... args);
17
18
Environment getEnvironment();
19
<T> ApplicationContext registerSingleton(Class<T> type, T singleton);
20
ApplicationContext start();
21
ApplicationContext stop();
22
}
23
```
24
25
### BeanContext
26
27
Core interface for bean resolution and management.
28
29
```java { .api }
30
public interface BeanContext extends BeanLocator {
31
<T> T getBean(Class<T> beanType);
32
<T> T getBean(Class<T> beanType, Qualifier<T> qualifier);
33
<T> Optional<T> findBean(Class<T> beanType);
34
<T> Optional<T> findBean(Class<T> beanType, Qualifier<T> qualifier);
35
<T> Collection<T> getBeansOfType(Class<T> beanType);
36
<T> Collection<T> getBeansOfType(Class<T> beanType, Qualifier<T> qualifier);
37
<T> BeanDefinition<T> getBeanDefinition(Class<T> beanType);
38
<T> BeanDefinition<T> getBeanDefinition(Class<T> beanType, Qualifier<T> qualifier);
39
<T> Collection<BeanDefinition<T>> getBeanDefinitions(Class<T> beanType);
40
boolean containsBean(Class<?> beanType);
41
<T> T createBean(Class<T> beanType);
42
<T> T createBean(Class<T> beanType, Qualifier<T> qualifier);
43
<T> void destroyBean(T bean);
44
}
45
```
46
47
### ApplicationContextBuilder
48
49
Builder for configuring ApplicationContext instances.
50
51
```java { .api }
52
public interface ApplicationContextBuilder {
53
ApplicationContextBuilder environments(String... environments);
54
ApplicationContextBuilder properties(Map<String, Object> properties);
55
ApplicationContextBuilder singletons(Object... beans);
56
ApplicationContextBuilder packages(String... packages);
57
ApplicationContextBuilder args(String... args);
58
ApplicationContext build();
59
}
60
```
61
62
## Usage Examples
63
64
### Basic Application Context
65
66
```java
67
import io.micronaut.context.ApplicationContext;
68
69
public class BasicExample {
70
public static void main(String[] args) {
71
// Create and start application context
72
try (ApplicationContext context = ApplicationContext.run()) {
73
// Get beans from context
74
MyService service = context.getBean(MyService.class);
75
service.doSomething();
76
} // Context automatically closed
77
}
78
}
79
```
80
81
### Configured Application Context
82
83
```java
84
import io.micronaut.context.ApplicationContext;
85
import java.util.Map;
86
87
public class ConfiguredExample {
88
public static void main(String[] args) {
89
ApplicationContext context = ApplicationContext.builder()
90
.environments("dev", "local")
91
.properties(Map.of(
92
"app.name", "MyApp",
93
"database.url", "jdbc:h2:mem:test"
94
))
95
.packages("com.example.services")
96
.build()
97
.start();
98
99
try {
100
MyService service = context.getBean(MyService.class);
101
service.process();
102
} finally {
103
context.close();
104
}
105
}
106
}
107
```
108
109
### Manual Bean Registration
110
111
```java
112
import io.micronaut.context.ApplicationContext;
113
114
public class ManualRegistrationExample {
115
public static void main(String[] args) {
116
try (ApplicationContext context = ApplicationContext.run()) {
117
// Register singleton instances
118
MyConfig config = new MyConfig("production");
119
context.registerSingleton(MyConfig.class, config);
120
121
// Create bean that depends on registered singleton
122
MyService service = context.getBean(MyService.class);
123
service.initialize();
124
}
125
}
126
}
127
```
128
129
### Bean Resolution with Qualifiers
130
131
```java
132
import io.micronaut.context.ApplicationContext;
133
import io.micronaut.context.Qualifier;
134
import io.micronaut.inject.qualifiers.Qualifiers;
135
136
public class QualifierExample {
137
public static void main(String[] args) {
138
try (ApplicationContext context = ApplicationContext.run()) {
139
// Get bean by type only
140
DatabaseService dbService = context.getBean(DatabaseService.class);
141
142
// Get bean with named qualifier
143
DatabaseService mysqlService = context.getBean(
144
DatabaseService.class,
145
Qualifiers.byName("mysql")
146
);
147
148
// Get all beans of a type
149
Collection<DatabaseService> allServices =
150
context.getBeansOfType(DatabaseService.class);
151
152
// Optional bean resolution
153
Optional<CacheService> cacheService =
154
context.findBean(CacheService.class);
155
}
156
}
157
}
158
```
159
160
## Bean Lifecycle Management
161
162
### Creating and Destroying Beans
163
164
```java
165
import io.micronaut.context.ApplicationContext;
166
167
public class LifecycleExample {
168
public static void main(String[] args) {
169
try (ApplicationContext context = ApplicationContext.run()) {
170
// Create prototype bean instances
171
PrototypeBean bean1 = context.createBean(PrototypeBean.class);
172
PrototypeBean bean2 = context.createBean(PrototypeBean.class);
173
174
// Use beans
175
bean1.doWork();
176
bean2.doWork();
177
178
// Manually destroy beans when done
179
context.destroyBean(bean1);
180
context.destroyBean(bean2);
181
}
182
}
183
}
184
```
185
186
### Checking Bean Availability
187
188
```java
189
import io.micronaut.context.ApplicationContext;
190
191
public class AvailabilityExample {
192
public static void main(String[] args) {
193
try (ApplicationContext context = ApplicationContext.run()) {
194
// Check if bean is available
195
if (context.containsBean(EmailService.class)) {
196
EmailService emailService = context.getBean(EmailService.class);
197
emailService.sendWelcomeEmail();
198
}
199
200
// Get all bean definitions for a type
201
Collection<BeanDefinition<MessageService>> definitions =
202
context.getBeanDefinitions(MessageService.class);
203
204
for (BeanDefinition<MessageService> def : definitions) {
205
System.out.println("Found bean: " + def.getBeanType());
206
}
207
}
208
}
209
}
210
```
211
212
## Implementation Classes
213
214
### DefaultApplicationContext
215
216
The default implementation of ApplicationContext.
217
218
```java { .api }
219
public class DefaultApplicationContext implements ApplicationContext {
220
public DefaultApplicationContext();
221
public DefaultApplicationContext(String... environments);
222
public DefaultApplicationContext(ApplicationContextConfiguration configuration);
223
224
// Implements all ApplicationContext methods
225
}
226
```
227
228
## Context Configuration
229
230
### ApplicationContextConfiguration
231
232
Configuration interface for customizing ApplicationContext behavior.
233
234
```java { .api }
235
public interface ApplicationContextConfiguration {
236
List<String> getEnvironments();
237
Optional<Boolean> isEagerInitSingletons();
238
Optional<Boolean> isEagerInitConfiguration();
239
ClassLoader getClassLoader();
240
}
241
```
242
243
## Error Handling
244
245
Common exceptions when working with ApplicationContext:
246
247
- **BeanContextException**: Base exception for context-related errors
248
- **NoSuchBeanException**: When a required bean cannot be found
249
- **NonUniqueBeanException**: When multiple beans match but only one expected
250
- **BeanInstantiationException**: When bean creation fails
251
252
```java
253
try (ApplicationContext context = ApplicationContext.run()) {
254
MyService service = context.getBean(MyService.class);
255
} catch (NoSuchBeanException e) {
256
System.err.println("Service not found: " + e.getMessage());
257
} catch (BeanInstantiationException e) {
258
System.err.println("Failed to create service: " + e.getMessage());
259
}
260
```