0
# Core Infrastructure
1
2
This section covers the fundamental Spring Core infrastructure APIs that provide the building blocks for dependency injection, component ordering, type resolution, and basic utilities.
3
4
## Ordering and Priority System
5
6
Spring provides a comprehensive ordering system for components that need to be sorted by priority.
7
8
**Basic Ordering Interface**
9
```java { .api }
10
public interface Ordered {
11
int HIGHEST_PRECEDENCE = Integer.MIN_VALUE;
12
int LOWEST_PRECEDENCE = Integer.MAX_VALUE;
13
int getOrder();
14
}
15
16
public interface PriorityOrdered extends Ordered {
17
// Marker interface for high-priority ordered objects
18
}
19
```
20
21
**Usage Examples**
22
```java
23
// Implement ordered components
24
public class DatabaseMigration implements Ordered {
25
@Override
26
public int getOrder() {
27
return 1; // High priority (low number)
28
}
29
}
30
31
public class CacheInitializer implements PriorityOrdered {
32
@Override
33
public int getOrder() {
34
return 0; // Even higher priority
35
}
36
}
37
38
// Use ordering comparator
39
List<Ordered> components = Arrays.asList(
40
new DatabaseMigration(),
41
new CacheInitializer()
42
);
43
OrderComparator.sort(components);
44
```
45
46
**Order Comparator**
47
```java { .api }
48
public class OrderComparator implements Comparator<Object> {
49
public static final OrderComparator INSTANCE = new OrderComparator();
50
51
public static void sort(List<?> list);
52
public static void sort(Object[] array);
53
54
@Override
55
public int compare(Object o1, Object o2);
56
protected int getOrder(Object obj);
57
}
58
```
59
60
## Type Resolution and Generics
61
62
Spring provides advanced type resolution capabilities for working with generic types and method parameters.
63
64
**ResolvableType API**
65
```java { .api }
66
public final class ResolvableType {
67
// Static factory methods
68
public static ResolvableType forField(Field field);
69
public static ResolvableType forMethodParameter(Method method, int parameterIndex);
70
public static ResolvableType forMethodParameter(MethodParameter methodParameter);
71
public static ResolvableType forMethodReturnType(Method method);
72
public static ResolvableType forClass(Class<?> clazz);
73
public static ResolvableType forClassWithGenerics(Class<?> clazz, Class<?>... generics);
74
public static ResolvableType forClassWithGenerics(Class<?> clazz, ResolvableType... generics);
75
public static ResolvableType forType(Type type);
76
public static ResolvableType forInstance(Object instance);
77
78
// Resolution methods
79
public Class<?> resolve();
80
public Class<?> resolve(Class<?> fallback);
81
public Class<?> toClass();
82
public Type getType();
83
public Class<?> getRawClass();
84
public Object getSource();
85
86
// Type hierarchy navigation
87
public ResolvableType getSuperType();
88
public ResolvableType[] getInterfaces();
89
public ResolvableType as(Class<?> type);
90
91
// Generic type access
92
public ResolvableType getGeneric(int... indexes);
93
public ResolvableType[] getGenerics();
94
public Class<?>[] resolveGenerics();
95
public Class<?>[] resolveGenerics(Class<?> fallback);
96
97
// Type checking
98
public boolean hasGenerics();
99
public boolean hasUnresolvableGenerics();
100
public boolean isAssignableFrom(Class<?> other);
101
public boolean isAssignableFrom(ResolvableType other);
102
public boolean isArray();
103
public boolean isInstance(Object obj);
104
}
105
```
106
107
**Usage Examples**
108
```java
109
// Resolve generic types from fields
110
public class GenericService<T, U> {
111
private List<T> items;
112
private Map<String, U> cache;
113
}
114
115
Field itemsField = GenericService.class.getDeclaredField("items");
116
ResolvableType fieldType = ResolvableType.forField(itemsField);
117
ResolvableType genericType = fieldType.getGeneric(0); // Gets T
118
119
// Resolve method parameter types
120
public void processItems(List<String> items, Map<Long, User> userMap) { }
121
122
Method method = MyClass.class.getMethod("processItems", List.class, Map.class);
123
ResolvableType listParam = ResolvableType.forMethodParameter(method, 0);
124
ResolvableType stringType = listParam.getGeneric(0); // String.class
125
126
ResolvableType mapParam = ResolvableType.forMethodParameter(method, 1);
127
ResolvableType keyType = mapParam.getGeneric(0); // Long.class
128
ResolvableType valueType = mapParam.getGeneric(1); // User.class
129
130
// Create types programmatically
131
ResolvableType stringListType = ResolvableType.forClassWithGenerics(List.class, String.class);
132
ResolvableType mapType = ResolvableType.forClassWithGenerics(
133
Map.class,
134
ResolvableType.forClass(String.class),
135
ResolvableType.forClass(Integer.class)
136
);
137
```
138
139
**MethodParameter API**
140
```java { .api }
141
public class MethodParameter {
142
// Constructors
143
public MethodParameter(Method method, int parameterIndex);
144
public MethodParameter(Constructor<?> constructor, int parameterIndex);
145
public MethodParameter(MethodParameter original);
146
147
// Parameter info
148
public Method getMethod();
149
public Constructor<?> getConstructor();
150
public Class<?> getDeclaringClass();
151
public Member getMember();
152
public AnnotatedElement getAnnotatedElement();
153
154
// Type information
155
public Class<?> getParameterType();
156
public Type getGenericParameterType();
157
public ResolvableType getResolvableType();
158
public int getParameterIndex();
159
160
// Annotations
161
public Annotation[] getParameterAnnotations();
162
public <A extends Annotation> A getParameterAnnotation(Class<A> annotationType);
163
public boolean hasParameterAnnotation(Class<? extends Annotation> annotationType);
164
165
// Parameter names and attributes
166
public String getParameterName();
167
public boolean isOptional();
168
public MethodParameter nested();
169
public MethodParameter nested(int nestingLevel);
170
public MethodParameter withTypeIndex(int typeIndex);
171
172
// Utility methods
173
public MethodParameter clone();
174
public void initParameterNameDiscovery(ParameterNameDiscoverer parameterNameDiscoverer);
175
}
176
```
177
178
**Usage Examples**
179
```java
180
// Analyze method parameters
181
public void handleRequest(@RequestParam String name,
182
@RequestBody Optional<User> user,
183
HttpServletRequest request) { }
184
185
Method method = MyController.class.getMethod("handleRequest",
186
String.class, Optional.class, HttpServletRequest.class);
187
188
// Inspect first parameter
189
MethodParameter nameParam = new MethodParameter(method, 0);
190
Class<?> paramType = nameParam.getParameterType(); // String.class
191
RequestParam annotation = nameParam.getParameterAnnotation(RequestParam.class);
192
193
// Inspect optional parameter
194
MethodParameter userParam = new MethodParameter(method, 1);
195
boolean isOptional = userParam.isOptional(); // true
196
MethodParameter nestedParam = userParam.nested(); // Gets Optional<User> -> User
197
Class<?> nestedType = nestedParam.getParameterType(); // User.class
198
```
199
200
## Alias Management
201
202
Spring provides alias management for component names and identifiers.
203
204
**AliasRegistry Interface**
205
```java { .api }
206
public interface AliasRegistry {
207
void registerAlias(String name, String alias);
208
void removeAlias(String alias);
209
boolean isAlias(String name);
210
String[] getAliases(String name);
211
}
212
213
public class SimpleAliasRegistry implements AliasRegistry, BeanNameAware {
214
public SimpleAliasRegistry();
215
216
@Override
217
public void registerAlias(String name, String alias);
218
@Override
219
public void removeAlias(String alias);
220
@Override
221
public boolean isAlias(String name);
222
@Override
223
public String[] getAliases(String name);
224
225
public String canonicalName(String name);
226
public boolean hasAlias(String name, String alias);
227
public void resolveAliases(StringValueResolver valueResolver);
228
}
229
```
230
231
**Usage Examples**
232
```java
233
// Register and use aliases
234
AliasRegistry registry = new SimpleAliasRegistry();
235
236
// Register aliases
237
registry.registerAlias("dataSource", "db");
238
registry.registerAlias("dataSource", "database");
239
registry.registerAlias("userService", "users");
240
241
// Check aliases
242
boolean isAlias = registry.isAlias("db"); // true
243
String[] aliases = registry.getAliases("dataSource"); // ["db", "database"]
244
245
// Remove aliases
246
registry.removeAlias("db");
247
```
248
249
## Attribute Access and Metadata
250
251
Spring provides a system for attaching arbitrary metadata to objects.
252
253
**AttributeAccessor Interface**
254
```java { .api }
255
public interface AttributeAccessor {
256
void setAttribute(String name, Object value);
257
Object getAttribute(String name);
258
Object removeAttribute(String name);
259
boolean hasAttribute(String name);
260
String[] attributeNames();
261
}
262
263
public class AttributeAccessorSupport implements AttributeAccessor, Serializable {
264
public AttributeAccessorSupport();
265
266
@Override
267
public void setAttribute(String name, Object value);
268
@Override
269
public Object getAttribute(String name);
270
@Override
271
public Object removeAttribute(String name);
272
@Override
273
public boolean hasAttribute(String name);
274
@Override
275
public String[] attributeNames();
276
277
protected void copyAttributesFrom(AttributeAccessor source);
278
}
279
```
280
281
**Usage Examples**
282
```java
283
// Attach metadata to objects
284
AttributeAccessor accessor = new AttributeAccessorSupport();
285
286
// Set attributes
287
accessor.setAttribute("created", Instant.now());
288
accessor.setAttribute("author", "john.doe");
289
accessor.setAttribute("version", "1.0");
290
291
// Get attributes
292
Instant created = (Instant) accessor.getAttribute("created");
293
String author = (String) accessor.getAttribute("author");
294
295
// Check and remove
296
if (accessor.hasAttribute("version")) {
297
Object version = accessor.removeAttribute("version");
298
}
299
300
// List all attributes
301
String[] names = accessor.attributeNames();
302
```
303
304
## Exception Handling
305
306
Spring provides base classes for nested exception handling with root cause tracking.
307
308
**Nested Exception Classes**
309
```java { .api }
310
public abstract class NestedRuntimeException extends RuntimeException {
311
public NestedRuntimeException(String msg);
312
public NestedRuntimeException(String msg, Throwable cause);
313
314
public String getMessage();
315
public Throwable getRootCause();
316
public Throwable getMostSpecificCause();
317
public boolean contains(Class<?> exType);
318
public static String buildMessage(String message, Throwable cause);
319
}
320
321
public abstract class NestedCheckedException extends Exception {
322
public NestedCheckedException(String msg);
323
public NestedCheckedException(String msg, Throwable cause);
324
325
public String getMessage();
326
public Throwable getRootCause();
327
public Throwable getMostSpecificCause();
328
public boolean contains(Class<?> exType);
329
public static String buildMessage(String message, Throwable cause);
330
}
331
```
332
333
**Usage Examples**
334
```java
335
// Create custom exceptions with nested support
336
public class DataAccessException extends NestedRuntimeException {
337
public DataAccessException(String msg) {
338
super(msg);
339
}
340
341
public DataAccessException(String msg, Throwable cause) {
342
super(msg, cause);
343
}
344
}
345
346
// Use nested exceptions
347
try {
348
// Some database operation
349
connection.execute(sql);
350
} catch (SQLException ex) {
351
// Wrap with more specific exception
352
throw new DataAccessException("Failed to execute query", ex);
353
}
354
355
// Handle nested exceptions
356
try {
357
someMethod();
358
} catch (DataAccessException ex) {
359
Throwable rootCause = ex.getRootCause(); // Gets original SQLException
360
Throwable mostSpecific = ex.getMostSpecificCause();
361
362
if (ex.contains(SQLException.class)) {
363
// Handle SQL-specific error
364
}
365
}
366
```
367
368
## Parameter Name Discovery
369
370
Spring provides mechanisms for discovering parameter names at runtime.
371
372
**ParameterNameDiscoverer Interface**
373
```java { .api }
374
public interface ParameterNameDiscoverer {
375
String[] getParameterNames(Method method);
376
String[] getParameterNames(Constructor<?> ctor);
377
}
378
379
public class DefaultParameterNameDiscoverer extends PrioritizedParameterNameDiscoverer {
380
public DefaultParameterNameDiscoverer();
381
}
382
383
public class PrioritizedParameterNameDiscoverer implements ParameterNameDiscoverer {
384
public void addDiscoverer(ParameterNameDiscoverer pnd);
385
386
@Override
387
public String[] getParameterNames(Method method);
388
@Override
389
public String[] getParameterNames(Constructor<?> ctor);
390
}
391
392
public class StandardReflectionParameterNameDiscoverer implements ParameterNameDiscoverer {
393
@Override
394
public String[] getParameterNames(Method method);
395
@Override
396
public String[] getParameterNames(Constructor<?> ctor);
397
}
398
```
399
400
**Usage Examples**
401
```java
402
// Discover parameter names
403
ParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
404
405
public void processUser(String firstName, String lastName, int age) { }
406
407
Method method = MyClass.class.getMethod("processUser", String.class, String.class, int.class);
408
String[] paramNames = discoverer.getParameterNames(method);
409
// Returns: ["firstName", "lastName", "age"] (if compiled with -parameters flag)
410
411
// Use with constructors
412
public class User {
413
public User(String name, String email, int age) { }
414
}
415
416
Constructor<?> constructor = User.class.getConstructor(String.class, String.class, int.class);
417
String[] constructorParams = discoverer.getParameterNames(constructor);
418
```
419
420
## Generic Type Resolution Utilities
421
422
**GenericTypeResolver Utility**
423
```java { .api }
424
public abstract class GenericTypeResolver {
425
public static Class<?> resolveParameterType(MethodParameter methodParameter, Class<?> implementationClass);
426
public static Class<?> resolveReturnType(Method method, Class<?> clazz);
427
public static Class<?> resolveReturnTypeArgument(Method method, Class<?> genericIfc);
428
public static Class<?> resolveTypeArgument(Class<?> clazz, Class<?> genericIfc);
429
public static Class<?>[] resolveTypeArguments(Class<?> clazz, Class<?> genericIfc);
430
431
public static Type resolveType(Type genericType, Class<?> contextClass);
432
public static Class<?> resolveType(Type genericType, Map<TypeVariable<?>, Type> map);
433
}
434
```
435
436
**Usage Examples**
437
```java
438
// Resolve generic types in inheritance hierarchies
439
public interface Repository<T> {
440
void save(T entity);
441
List<T> findAll();
442
}
443
444
public class UserRepository implements Repository<User> {
445
// Implementation
446
}
447
448
// Resolve the generic type T = User
449
Class<?> entityType = GenericTypeResolver.resolveTypeArgument(
450
UserRepository.class, Repository.class); // Returns User.class
451
452
// Resolve method return types
453
Method findAllMethod = Repository.class.getMethod("findAll");
454
Class<?> returnType = GenericTypeResolver.resolveReturnType(
455
findAllMethod, UserRepository.class); // Returns List.class
456
457
Class<?> elementType = GenericTypeResolver.resolveReturnTypeArgument(
458
findAllMethod, UserRepository.class); // Returns User.class
459
```
460
461
## Spring Framework Version Information
462
463
**SpringVersion Utility**
464
```java { .api }
465
public final class SpringVersion {
466
public static String getVersion();
467
468
// Private constructor - utility class
469
}
470
```
471
472
**Usage Example**
473
```java
474
// Get Spring version at runtime
475
String version = SpringVersion.getVersion(); // e.g., "6.2.8"
476
System.out.println("Running Spring Framework version: " + version);
477
```
478
479
## Type Definitions
480
481
**Core Callback Interfaces**
482
```java { .api }
483
@FunctionalInterface
484
public interface MethodCallback {
485
void doWith(Method method) throws IllegalArgumentException, IllegalAccessException;
486
}
487
488
@FunctionalInterface
489
public interface FieldCallback {
490
void doWith(Field field) throws IllegalArgumentException, IllegalAccessException;
491
}
492
493
@FunctionalInterface
494
public interface MethodFilter {
495
boolean matches(Method method);
496
497
MethodFilter USER_DECLARED_METHODS = (method -> !method.isBridge() && !method.isSynthetic());
498
}
499
500
@FunctionalInterface
501
public interface FieldFilter {
502
boolean matches(Field field);
503
}
504
```
505
506
**Exception Depth Comparator**
507
```java { .api }
508
public class ExceptionDepthComparator implements Comparator<Class<? extends Throwable>> {
509
public ExceptionDepthComparator(Throwable exception);
510
public ExceptionDepthComparator(Class<? extends Throwable> targetException);
511
512
@Override
513
public int compare(Class<? extends Throwable> o1, Class<? extends Throwable> o2);
514
515
public static Class<? extends Throwable> findClosestMatch(
516
Collection<Class<? extends Throwable>> exceptionTypes,
517
Throwable targetException);
518
}
519
```
520
521
This core infrastructure provides the foundational building blocks that enable Spring's dependency injection container, aspect-oriented programming capabilities, and other advanced features throughout the framework.