0
# Micronaut Context
1
2
Micronaut Context is a core library module for the Micronaut Framework that extends the micronaut-inject module with additional bean container services. It provides advanced application runtime features including declarative job scheduling with @Scheduled annotations, reactive event handling with @EventListener annotations, and support for immutable configuration properties. The module serves as the foundation for building enterprise-grade JVM applications with features like application lifecycle management, graceful shutdown, configuration binding, and runtime bean management.
3
4
## Package Information
5
6
- **Package Name**: io.micronaut:micronaut-context
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**: Add to your Maven `pom.xml` or Gradle `build.gradle`:
10
11
Maven:
12
```xml
13
<dependency>
14
<groupId>io.micronaut</groupId>
15
<artifactId>micronaut-context</artifactId>
16
<version>4.9.4</version>
17
</dependency>
18
```
19
20
Gradle:
21
```groovy
22
implementation 'io.micronaut:micronaut-context:4.9.4'
23
```
24
25
## Core Imports
26
27
```java
28
import io.micronaut.runtime.Micronaut;
29
import io.micronaut.context.ApplicationContext;
30
import io.micronaut.scheduling.annotation.Scheduled;
31
import io.micronaut.runtime.event.annotation.EventListener;
32
import io.micronaut.runtime.context.scope.Refreshable;
33
```
34
35
## Basic Usage
36
37
```java
38
import io.micronaut.runtime.Micronaut;
39
import io.micronaut.context.ApplicationContext;
40
41
public class Application {
42
public static void main(String[] args) {
43
// Start Micronaut application
44
ApplicationContext context = Micronaut.run(Application.class, args);
45
46
// Application runs until shutdown
47
// Context automatically manages lifecycle
48
}
49
}
50
51
// Scheduled task example
52
import io.micronaut.scheduling.annotation.Scheduled;
53
import jakarta.inject.Singleton;
54
55
@Singleton
56
public class TaskService {
57
@Scheduled(fixedDelay = "30s")
58
public void performMaintenanceTask() {
59
System.out.println("Running maintenance task");
60
}
61
62
@Scheduled(cron = "0 0 2 * * ?") // Daily at 2 AM
63
public void performDailyBackup() {
64
System.out.println("Running daily backup");
65
}
66
}
67
68
// Event listener example
69
import io.micronaut.runtime.event.annotation.EventListener;
70
import io.micronaut.runtime.server.event.ServerStartupEvent;
71
import jakarta.inject.Singleton;
72
73
@Singleton
74
public class StartupListener {
75
@EventListener
76
public void onStartup(ServerStartupEvent event) {
77
System.out.println("Server started on: " + event.getSource().getURL());
78
}
79
}
80
```
81
82
## Architecture
83
84
Micronaut Context is built around several key architectural components:
85
86
- **Application Runtime**: Core `Micronaut` class for bootstrapping and lifecycle management
87
- **Scheduling Engine**: Annotation-driven task scheduling with CRON and fixed-rate support
88
- **Event System**: Reactive event publishing and listening with @EventListener
89
- **Scope Management**: Custom scopes including @Refreshable and @ThreadLocal
90
- **Server Abstraction**: Embedded server lifecycle management and configuration
91
- **Graceful Shutdown**: Coordinated shutdown of application components
92
- **Executor Framework**: Thread pool management and task execution
93
94
## Capabilities
95
96
### Application Runtime
97
98
Core application bootstrapping and lifecycle management. The main entry point for running Micronaut applications with configuration support and embedded server management.
99
100
```java { .api }
101
public class Micronaut extends DefaultApplicationContextBuilder {
102
public static ApplicationContext run(String... args);
103
public static ApplicationContext run(Class<?> cls, String... args);
104
public static ApplicationContext run(Class<?>[] classes, String... args);
105
public static Micronaut build(String... args);
106
public ApplicationContext start();
107
}
108
109
public interface EmbeddedApplication<T> extends ApplicationContextLifeCycle<T> {
110
ApplicationContext getApplicationContext();
111
ApplicationConfiguration getApplicationConfiguration();
112
Environment getEnvironment();
113
boolean isServer();
114
boolean isForceExit();
115
boolean isShutdownHookNeeded();
116
}
117
```
118
119
[Application Runtime](./runtime.md)
120
121
### Task Scheduling
122
123
Declarative and programmatic task scheduling with CRON expressions, fixed delays, and custom executors. Supports both annotation-driven scheduling and programmatic task management.
124
125
```java { .api }
126
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
127
@Retention(RetentionPolicy.RUNTIME)
128
@Repeatable(Schedules.class)
129
public @interface Scheduled {
130
String cron() default "";
131
String zoneId() default "";
132
String fixedDelay() default "";
133
String initialDelay() default "";
134
String fixedRate() default "";
135
String scheduler() default TaskExecutors.SCHEDULED;
136
String condition() default "";
137
}
138
139
public interface TaskScheduler {
140
ScheduledFuture<?> schedule(String cron, Runnable command);
141
<V> ScheduledFuture<V> schedule(String cron, Callable<V> command);
142
ScheduledFuture<?> schedule(Duration delay, Runnable command);
143
ScheduledFuture<?> scheduleAtFixedRate(Duration initialDelay, Duration period, Runnable command);
144
ScheduledFuture<?> scheduleWithFixedDelay(Duration initialDelay, Duration delay, Runnable command);
145
}
146
```
147
148
[Task Scheduling](./scheduling.md)
149
150
### Event System
151
152
Application event publishing and listening with reactive support. Enables decoupled communication between application components through typed events.
153
154
```java { .api }
155
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
156
@Retention(RetentionPolicy.RUNTIME)
157
@Adapter(ApplicationEventListener.class)
158
public @interface EventListener {
159
}
160
161
public class ApplicationStartupEvent extends AbstractEmbeddedApplicationEvent {
162
public ApplicationStartupEvent(EmbeddedApplication<?> source);
163
}
164
165
public class ApplicationShutdownEvent extends AbstractEmbeddedApplicationEvent {
166
public ApplicationShutdownEvent(EmbeddedApplication<?> source);
167
}
168
```
169
170
[Event System](./events.md)
171
172
### Scope Management
173
174
Custom bean scopes including refreshable configurations and thread-local storage. Enables advanced bean lifecycle management beyond singleton and prototype scopes.
175
176
```java { .api }
177
@Target({ElementType.TYPE, ElementType.METHOD})
178
@Retention(RetentionPolicy.RUNTIME)
179
@Scope
180
@ScopedProxy
181
public @interface Refreshable {
182
String[] value() default {};
183
}
184
185
@Target({ElementType.TYPE, ElementType.METHOD})
186
@Retention(RetentionPolicy.RUNTIME)
187
@Scope
188
@ScopedProxy
189
public @interface ThreadLocal {
190
boolean lifecycle() default false;
191
}
192
193
public class RefreshEvent extends ApplicationEvent {
194
public RefreshEvent(Map<String, Object> changes);
195
public RefreshEvent();
196
public Map<String, Object> getSource();
197
}
198
```
199
200
[Scope Management](./scopes.md)
201
202
### Server Lifecycle
203
204
Embedded server abstraction and lifecycle events. Provides unified interface for different server implementations with startup/shutdown coordination.
205
206
```java { .api }
207
public interface EmbeddedServer extends EmbeddedApplication<EmbeddedServer> {
208
int getPort();
209
String getHost();
210
String getScheme();
211
URL getURL();
212
URI getURI();
213
URI getContextURI();
214
boolean isKeepAlive();
215
}
216
217
public class ServerStartupEvent extends ApplicationStartupEvent {
218
public ServerStartupEvent(EmbeddedServer embeddedServer);
219
public EmbeddedServer getSource();
220
}
221
222
public class ServerShutdownEvent {
223
// Event fired when EmbeddedServer shuts down
224
}
225
```
226
227
[Server Lifecycle](./server.md)
228
229
### Graceful Shutdown
230
231
Coordinated shutdown capabilities for application components. Enables clean resource cleanup and graceful termination of long-running operations.
232
233
```java { .api }
234
public interface GracefulShutdownCapable {
235
CompletionStage<?> shutdownGracefully();
236
OptionalLong reportActiveTasks();
237
static CompletionStage<?> allOf(Stream<CompletionStage<?>> stages);
238
static CompletionStage<?> shutdownAll(Stream<? extends GracefulShutdownCapable> stages);
239
}
240
241
@Singleton
242
public class GracefulShutdownManager {
243
public CompletionStage<?> shutdownGracefully();
244
public OptionalLong reportActiveTasks();
245
}
246
```
247
248
[Graceful Shutdown](./shutdown.md)
249
250
## Core Types
251
252
```java { .api }
253
public class ApplicationConfiguration {
254
public static final String PREFIX = "micronaut.application";
255
public static final String APPLICATION_NAME = "micronaut.application.name";
256
257
public Charset getDefaultCharset();
258
public Optional<String> getName();
259
public InstanceConfiguration getInstance();
260
}
261
262
public interface TaskExecutors {
263
String IO = "io";
264
String BLOCKING = "blocking";
265
String VIRTUAL = "virtual";
266
String SCHEDULED = "scheduled";
267
String MESSAGE_CONSUMER = "consumer";
268
}
269
270
public class CronExpression {
271
public static CronExpression create(String cronExpression);
272
public ZonedDateTime nextExecution(ZonedDateTime lastExecution);
273
public boolean matches(ZonedDateTime dateTime);
274
}
275
276
public enum LogLevel {
277
ALL, TRACE, DEBUG, INFO, WARN, ERROR, OFF, NOT_SPECIFIED
278
}
279
```