Spring Context module providing application context and dependency injection capabilities
npx @tessl/cli install tessl/maven-org-springframework--spring-context@6.2.00
# Spring Context
1
2
Spring Context is the core module of the Spring Framework that provides comprehensive application context and dependency injection capabilities. It implements the Inversion of Control (IoC) container that manages object lifecycle, dependency resolution, and bean configuration through annotations, XML, or Java-based configuration. The module supports advanced features including aspect-oriented programming integration, event handling, internationalization, validation, scheduled task execution, and integration with Jakarta EE specifications.
3
4
## Package Information
5
6
- **Package Name**: org.springframework:spring-context
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**: Add to Maven `pom.xml`:
10
11
```xml
12
<dependency>
13
<groupId>org.springframework</groupId>
14
<artifactId>spring-context</artifactId>
15
<version>6.2.8</version>
16
</dependency>
17
```
18
19
For Gradle `build.gradle`:
20
21
```gradle
22
implementation 'org.springframework:spring-context:6.2.8'
23
```
24
25
## Core Imports
26
27
```java
28
import org.springframework.context.ApplicationContext;
29
import org.springframework.context.ConfigurableApplicationContext;
30
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
31
import org.springframework.context.annotation.Configuration;
32
import org.springframework.context.annotation.Bean;
33
import org.springframework.context.annotation.ComponentScan;
34
import org.springframework.stereotype.Component;
35
import org.springframework.stereotype.Service;
36
import org.springframework.stereotype.Repository;
37
import org.springframework.beans.factory.annotation.Autowired;
38
```
39
40
## Basic Usage
41
42
```java
43
import org.springframework.context.ApplicationContext;
44
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
45
import org.springframework.context.annotation.Configuration;
46
import org.springframework.context.annotation.Bean;
47
import org.springframework.context.annotation.ComponentScan;
48
import org.springframework.stereotype.Service;
49
50
// Configuration class
51
@Configuration
52
@ComponentScan(basePackages = "com.example")
53
public class AppConfig {
54
55
@Bean
56
public UserService userService() {
57
return new UserService();
58
}
59
}
60
61
// Service component
62
@Service
63
public class UserService {
64
public String getUser() {
65
return "John Doe";
66
}
67
}
68
69
// Application startup
70
public class Application {
71
public static void main(String[] args) {
72
// Create application context
73
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
74
75
// Retrieve beans
76
UserService userService = context.getBean(UserService.class);
77
String user = userService.getUser();
78
79
System.out.println("User: " + user);
80
81
// Close context (if configurable)
82
if (context instanceof ConfigurableApplicationContext) {
83
((ConfigurableApplicationContext) context).close();
84
}
85
}
86
}
87
```
88
89
## Architecture
90
91
Spring Context is built around several key architectural components:
92
93
- **IoC Container**: The core container that manages bean definitions, lifecycle, and dependencies
94
- **ApplicationContext**: The central interface providing configuration and runtime environment for applications
95
- **Bean Factory**: The underlying factory for creating and managing bean instances
96
- **Configuration Processing**: Support for annotation-based, XML-based, and Java-based configuration
97
- **Event System**: Publish-subscribe mechanism for application events and listeners
98
- **Lifecycle Management**: Automatic startup/shutdown handling and bean lifecycle callbacks
99
- **Resource Loading**: Unified resource abstraction for loading configuration and other resources
100
- **Environment Abstraction**: Property source management and profile-based configuration
101
102
## Capabilities
103
104
### Application Context
105
106
Core ApplicationContext interfaces and implementations providing the foundation for dependency injection and application configuration. Includes context lifecycle management, hierarchical contexts, and various implementation strategies.
107
108
```java { .api }
109
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory,
110
HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
111
String getId();
112
String getApplicationName();
113
String getDisplayName();
114
long getStartupDate();
115
ApplicationContext getParent();
116
AutowireCapableBeanFactory getAutowireCapableBeanFactory();
117
}
118
119
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {
120
void setId(String id);
121
void setParent(ApplicationContext parent);
122
void setEnvironment(ConfigurableEnvironment environment);
123
void refresh();
124
void registerShutdownHook();
125
void close();
126
boolean isActive();
127
ConfigurableListableBeanFactory getBeanFactory();
128
}
129
```
130
131
[Application Context](./application-context.md)
132
133
### Annotation Configuration
134
135
Annotation-driven configuration including @Configuration classes, @Bean methods, component scanning, and import mechanisms. Provides the foundation for modern Java-based Spring configuration.
136
137
```java { .api }
138
@Configuration
139
public @interface Configuration {
140
String value() default "";
141
boolean proxyBeanMethods() default true;
142
boolean enforceUniqueMethods() default true;
143
}
144
145
@Bean
146
public @interface Bean {
147
String[] value() default {};
148
String[] name() default {};
149
String initMethod() default "";
150
String destroyMethod() default "";
151
}
152
153
@ComponentScan
154
public @interface ComponentScan {
155
String[] value() default {};
156
String[] basePackages() default {};
157
Class<?>[] basePackageClasses() default {};
158
boolean useDefaultFilters() default true;
159
}
160
```
161
162
[Annotation Configuration](./annotation-configuration.md)
163
164
### Dependency Injection
165
166
IoC container functionality including bean definitions, autowiring, scope management, and dependency resolution. Covers both programmatic and declarative approaches to dependency injection.
167
168
```java { .api }
169
public interface BeanFactory {
170
Object getBean(String name);
171
<T> T getBean(String name, Class<T> requiredType);
172
<T> T getBean(Class<T> requiredType);
173
boolean containsBean(String name);
174
boolean isSingleton(String name);
175
boolean isPrototype(String name);
176
}
177
178
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
179
@Retention(RetentionPolicy.RUNTIME)
180
public @interface Autowired {
181
boolean required() default true;
182
}
183
```
184
185
[Dependency Injection](./dependency-injection.md)
186
187
### Event Handling
188
189
Application event system with @EventListener annotations, event publishing, and multicasting. Supports synchronous and asynchronous event processing with conditional handling.
190
191
```java { .api }
192
@EventListener
193
public @interface EventListener {
194
Class<?>[] classes() default {};
195
String condition() default "";
196
String id() default "";
197
}
198
199
public interface ApplicationEventPublisher {
200
default void publishEvent(ApplicationEvent event) {}
201
default void publishEvent(Object event) {}
202
}
203
204
public abstract class ApplicationEvent extends EventObject {
205
public final long getTimestamp() {}
206
}
207
```
208
209
[Event Handling](./event-handling.md)
210
211
### Scheduling
212
213
Task scheduling and asynchronous execution with @Scheduled and @Async annotations. Includes task schedulers, executors, and timing configuration options.
214
215
```java { .api }
216
@Scheduled
217
public @interface Scheduled {
218
String cron() default "";
219
String zone() default "";
220
long fixedDelay() default -1;
221
long fixedRate() default -1;
222
long initialDelay() default -1;
223
TimeUnit timeUnit() default TimeUnit.MILLISECONDS;
224
}
225
226
@Async
227
public @interface Async {
228
String value() default "";
229
}
230
231
public interface TaskScheduler {
232
ScheduledFuture<?> schedule(Runnable task, Trigger trigger);
233
ScheduledFuture<?> schedule(Runnable task, Instant startTime);
234
ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period);
235
}
236
```
237
238
[Scheduling](./scheduling.md)
239
240
### Caching
241
242
Declarative caching with @Cacheable, @CachePut, and @CacheEvict annotations. Includes cache managers, key generation, and cache abstraction layer.
243
244
```java { .api }
245
@Cacheable
246
public @interface Cacheable {
247
String[] value() default {};
248
String[] cacheNames() default {};
249
String key() default "";
250
String condition() default "";
251
String unless() default "";
252
boolean sync() default false;
253
}
254
255
public interface Cache {
256
String getName();
257
Object getNativeCache();
258
ValueWrapper get(Object key);
259
<T> T get(Object key, Class<T> type);
260
void put(Object key, Object value);
261
void evict(Object key);
262
void clear();
263
}
264
265
public interface CacheManager {
266
Cache getCache(String name);
267
Collection<String> getCacheNames();
268
}
269
```
270
271
[Caching](./caching.md)
272
273
### Validation
274
275
Bean validation and data binding with JSR-303/349 integration, Validator interfaces, and error handling. Supports both programmatic and declarative validation.
276
277
```java { .api }
278
public interface Validator {
279
boolean supports(Class<?> clazz);
280
void validate(Object target, Errors errors);
281
}
282
283
public interface SmartValidator extends Validator {
284
void validate(Object target, Errors errors, Object... validationHints);
285
default void validateValue(Class<?> targetType, String fieldName, Object value,
286
Errors errors, Object... validationHints) {}
287
}
288
289
@Validated
290
public @interface Validated {
291
Class<?>[] value() default {};
292
}
293
```
294
295
[Validation](./validation.md)
296
297
### Formatting
298
299
Type conversion and formatting with Formatter interfaces, @DateTimeFormat and @NumberFormat annotations. Handles conversion between strings and objects for web binding.
300
301
```java { .api }
302
public interface Formatter<T> extends Printer<T>, Parser<T> {
303
String print(T object, Locale locale);
304
T parse(String text, Locale locale);
305
}
306
307
@DateTimeFormat
308
public @interface DateTimeFormat {
309
String style() default "SS";
310
ISO iso() default ISO.NONE;
311
String pattern() default "";
312
String[] fallbackPatterns() default {};
313
}
314
315
@NumberFormat
316
public @interface NumberFormat {
317
Style style() default Style.DEFAULT;
318
String pattern() default "";
319
}
320
```
321
322
[Formatting](./formatting.md)
323
324
### Lifecycle Management
325
326
Bean lifecycle management including initialization, destruction, startup/shutdown phases, and lifecycle callbacks. Provides fine-grained control over component lifecycle.
327
328
```java { .api }
329
public interface Lifecycle {
330
void start();
331
void stop();
332
boolean isRunning();
333
}
334
335
public interface SmartLifecycle extends Lifecycle, Phased {
336
default boolean isAutoStartup() { return true; }
337
default void stop(Runnable callback) { stop(); callback.run(); }
338
default int getPhase() { return DEFAULT_PHASE; }
339
}
340
341
public interface InitializingBean {
342
void afterPropertiesSet() throws Exception;
343
}
344
345
public interface DisposableBean {
346
void destroy() throws Exception;
347
}
348
```
349
350
[Lifecycle Management](./lifecycle-management.md)
351
352
### Configuration Properties
353
354
Environment abstraction and property source management including profiles, property resolution, and @ConfigurationProperties binding for type-safe configuration.
355
356
```java { .api }
357
public interface Environment extends PropertyResolver {
358
String[] getActiveProfiles();
359
String[] getDefaultProfiles();
360
boolean acceptsProfiles(Profiles profiles);
361
}
362
363
public interface ConfigurableEnvironment extends Environment, ConfigurablePropertyResolver {
364
void setActiveProfiles(String... profiles);
365
void addActiveProfile(String profile);
366
void setDefaultProfiles(String... profiles);
367
MutablePropertySources getPropertySources();
368
}
369
370
@ConfigurationProperties
371
public @interface ConfigurationProperties {
372
String value() default "";
373
String prefix() default "";
374
boolean ignoreInvalidFields() default false;
375
boolean ignoreUnknownFields() default true;
376
}
377
```
378
379
[Configuration Properties](./configuration-properties.md)