0
# Spring Framework
1
2
The Spring Framework is a comprehensive application framework and inversion of control container for the Java platform. It provides a complete programming and configuration model for modern Java-based enterprise applications, with extensive infrastructure support for developing Java applications.
3
4
## Package Information
5
6
**Maven Coordinates:**
7
```xml
8
<dependency>
9
<groupId>org.springframework</groupId>
10
<artifactId>spring-context</artifactId>
11
<version>5.3.39</version>
12
</dependency>
13
```
14
15
**Gradle:**
16
```kotlin
17
implementation("org.springframework:spring-context:5.3.39")
18
```
19
20
**Java Version:** Requires Java 8 or higher
21
22
**Key Dependencies:**
23
- Spring uses SLF4J for logging
24
- Optional dependencies include Jackson for JSON processing, AspectJ for AOP
25
- Integration available with Hibernate, JPA, R2DBC, and other persistence frameworks
26
27
## Core Imports
28
29
### Essential Imports for Getting Started
30
31
```java { .api }
32
// Core Application Context
33
import org.springframework.context.ApplicationContext;
34
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
35
36
// Configuration and Component Scanning
37
import org.springframework.context.annotation.Configuration;
38
import org.springframework.context.annotation.ComponentScan;
39
import org.springframework.context.annotation.Bean;
40
41
// Dependency Injection Annotations
42
import org.springframework.beans.factory.annotation.Autowired;
43
import org.springframework.stereotype.Component;
44
import org.springframework.stereotype.Service;
45
import org.springframework.stereotype.Repository;
46
47
// Value Injection and Profiles
48
import org.springframework.beans.factory.annotation.Value;
49
import org.springframework.context.annotation.Profile;
50
```
51
52
### Resource and Property Management
53
54
```java { .api }
55
import org.springframework.core.io.Resource;
56
import org.springframework.core.io.ClassPathResource;
57
import org.springframework.core.env.Environment;
58
import org.springframework.context.annotation.PropertySource;
59
```
60
61
## Basic Usage
62
63
### Simple Spring Application
64
65
```java { .api }
66
@Configuration
67
@ComponentScan(basePackages = "com.example")
68
public class AppConfig {
69
70
@Bean
71
public DataService dataService() {
72
return new DataServiceImpl();
73
}
74
}
75
76
@Component
77
public class BusinessService {
78
79
@Autowired
80
private DataService dataService;
81
82
public String processData(String input) {
83
return dataService.transform(input);
84
}
85
}
86
87
// Application startup
88
public class Application {
89
public static void main(String[] args) {
90
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
91
BusinessService service = context.getBean(BusinessService.class);
92
String result = service.processData("hello");
93
System.out.println(result);
94
}
95
}
96
```
97
98
### Property-Driven Configuration
99
100
```java { .api }
101
@Configuration
102
@PropertySource("classpath:application.properties")
103
public class DatabaseConfig {
104
105
@Value("${db.url}")
106
private String dbUrl;
107
108
@Value("${db.username}")
109
private String dbUsername;
110
111
@Bean
112
public DataSource dataSource() {
113
BasicDataSource dataSource = new BasicDataSource();
114
dataSource.setUrl(dbUrl);
115
dataSource.setUsername(dbUsername);
116
return dataSource;
117
}
118
}
119
```
120
121
## Architecture
122
123
### Core Architecture Components
124
125
Spring Framework is built on several foundational layers:
126
127
#### 1. Core Container
128
- **Spring Core**: Fundamental utilities, type conversion, and IoC container foundation
129
- **Spring Beans**: Bean instantiation, dependency injection, and lifecycle management
130
- **Spring Context**: Application context, events, validation, and internationalization
131
- **Spring Expression**: Spring Expression Language (SpEL) for dynamic property access
132
133
#### 2. Data Access Layer
134
- **Spring JDBC**: Simplified JDBC operations and exception handling
135
- **Spring Transaction**: Declarative and programmatic transaction management
136
- **Spring ORM**: Integration with Hibernate, JPA, and other ORM frameworks
137
- **Spring R2DBC**: Reactive database connectivity support
138
139
#### 3. Web Layer
140
- **Spring Web**: Web application utilities and WebApplicationContext
141
- **Spring WebMVC**: Traditional servlet-based MVC framework
142
- **Spring WebFlux**: Reactive web framework for non-blocking applications
143
144
#### 4. Integration Layer
145
- **Spring AOP**: Aspect-oriented programming with method interception
146
- **Spring Messaging**: Message-driven applications and abstractions
147
- **Spring JMS**: Java Message Service integration
148
- **Spring WebSocket**: WebSocket support for real-time communication
149
150
### Dependency Injection Container
151
152
```java { .api }
153
// Container interfaces
154
public interface BeanFactory {
155
Object getBean(String name) throws BeansException;
156
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
157
<T> T getBean(Class<T> requiredType) throws BeansException;
158
boolean containsBean(String name);
159
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
160
}
161
162
public interface ApplicationContext extends BeanFactory, MessageSource,
163
ApplicationEventPublisher, ResourceLoader {
164
String getId();
165
String getApplicationName();
166
String getDisplayName();
167
long getStartupDate();
168
ApplicationContext getParent();
169
AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;
170
}
171
```
172
173
## Capabilities
174
175
### Core Container & Dependency Injection
176
177
The Spring IoC container manages object creation, dependency injection, and lifecycle. It supports various injection methods including constructor injection, setter injection, and field injection.
178
179
**Key APIs:**
180
```java { .api }
181
// Bean Definition and Configuration
182
public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {
183
String getBeanClassName();
184
void setBeanClassName(String beanClassName);
185
String getScope();
186
void setScope(String scope);
187
boolean isLazyInit();
188
String[] getDependsOn();
189
}
190
191
// Property Access and Type Conversion
192
public interface BeanWrapper extends ConfigurablePropertyAccessor {
193
Object getWrappedInstance();
194
Class<?> getWrappedClass();
195
PropertyDescriptor[] getPropertyDescriptors();
196
PropertyDescriptor getPropertyDescriptor(String propertyName)
197
throws InvalidPropertyException;
198
}
199
```
200
201
For comprehensive details: [Core Container & Dependency Injection](core-container.md)
202
203
### Aspect-Oriented Programming (AOP)
204
205
Spring AOP provides aspect-oriented programming implementation allowing you to define method interceptors and pointcuts to cleanly decouple functionality.
206
207
**Key APIs:**
208
```java { .api }
209
// Core AOP interfaces
210
public interface MethodInterceptor extends Interceptor {
211
Object invoke(MethodInvocation invocation) throws Throwable;
212
}
213
214
public interface Pointcut {
215
ClassFilter getClassFilter();
216
MethodMatcher getMethodMatcher();
217
}
218
219
// Proxy creation
220
public class ProxyFactory extends AdvisedSupport {
221
public Object getProxy();
222
public Object getProxy(ClassLoader classLoader);
223
public static <T> T getProxy(Class<T> proxyInterface, Interceptor interceptor);
224
}
225
```
226
227
For comprehensive details: [Aspect-Oriented Programming](aop.md)
228
229
### Data Access & Transaction Management
230
231
Spring provides abstraction over JDBC, transaction management, and integration with ORM frameworks like Hibernate and JPA.
232
233
**Key APIs:**
234
```java { .api }
235
// JDBC Template
236
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
237
public <T> T queryForObject(String sql, Class<T> requiredType, Object... args);
238
public <T> List<T> query(String sql, RowMapper<T> rowMapper, Object... args);
239
public int update(String sql, Object... args);
240
}
241
242
// Transaction Management
243
@Target({ElementType.METHOD, ElementType.TYPE})
244
@Retention(RetentionPolicy.RUNTIME)
245
@Inherited
246
@Documented
247
public @interface Transactional {
248
Propagation propagation() default Propagation.REQUIRED;
249
Isolation isolation() default Isolation.DEFAULT;
250
int timeout() default TransactionDefinition.TIMEOUT_DEFAULT;
251
boolean readOnly() default false;
252
}
253
```
254
255
For comprehensive details: [Data Access & Transaction Management](data-access.md)
256
257
### Web Framework (Spring MVC)
258
259
Spring MVC provides Model-View-Controller architecture for building web applications with flexible request handling and view resolution.
260
261
**Key APIs:**
262
```java { .api }
263
// Controller annotations
264
@Target({ElementType.TYPE})
265
@Retention(RetentionPolicy.RUNTIME)
266
@Documented
267
@Component
268
public @interface Controller {
269
String value() default "";
270
}
271
272
@Target({ElementType.METHOD})
273
@Retention(RetentionPolicy.RUNTIME)
274
@Documented
275
@Mapping
276
public @interface RequestMapping {
277
String[] value() default {};
278
RequestMethod[] method() default {};
279
String[] params() default {};
280
String[] headers() default {};
281
}
282
```
283
284
For comprehensive details: [Web Framework (Spring MVC)](web-framework.md)
285
286
### Reactive Web Framework (WebFlux)
287
288
Spring WebFlux provides reactive programming model for building non-blocking web applications using Reactor and reactive streams.
289
290
**Key APIs:**
291
```java { .api }
292
// Functional routing
293
public interface RouterFunction<T extends ServerResponse> {
294
Mono<HandlerFunction<T>> route(ServerRequest request);
295
RouterFunction<T> and(RouterFunction<T> other);
296
RouterFunction<T> andRoute(RequestPredicate predicate, HandlerFunction<T> handlerFunction);
297
}
298
299
// Reactive request/response
300
public interface ServerRequest {
301
Mono<String> bodyToMono(Class<String> elementClass);
302
<T> Flux<T> bodyToFlux(Class<T> elementClass);
303
MultiValueMap<String, String> queryParams();
304
}
305
```
306
307
For comprehensive details: [Reactive Web Framework (WebFlux)](reactive-web.md)
308
309
### Testing Support
310
311
Spring Test provides comprehensive testing utilities including TestContext framework, MockMvc for web layer testing, and transaction rollback support.
312
313
**Key APIs:**
314
```java { .api }
315
// Test annotations
316
@Target(ElementType.TYPE)
317
@Retention(RetentionPolicy.RUNTIME)
318
@Documented
319
@Inherited
320
@BootstrapWith(SpringBootTestContextBootstrapper.class)
321
public @interface SpringBootTest {
322
Class<?>[] classes() default {};
323
String[] properties() default {};
324
WebEnvironment webEnvironment() default WebEnvironment.MOCK;
325
}
326
327
// MockMvc for web testing
328
public final class MockMvc {
329
public ResultActions perform(RequestBuilder requestBuilder) throws Exception;
330
}
331
```
332
333
For comprehensive details: [Testing Support](testing.md)
334
335
### Messaging & JMS
336
337
Spring provides abstractions for message-driven applications including support for JMS, AMQP, and custom messaging solutions.
338
339
**Key APIs:**
340
```java { .api }
341
// Message abstraction
342
public interface Message<T> {
343
T getPayload();
344
MessageHeaders getHeaders();
345
}
346
347
// JMS Template
348
public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations {
349
public void send(String destinationName, MessageCreator messageCreator) throws JmsException;
350
public Object receiveAndConvert(String destinationName) throws JmsException;
351
}
352
```
353
354
For comprehensive details: [Messaging & JMS](messaging.md)
355
356
### Integration & Support
357
358
Additional Spring modules provide integration with various enterprise technologies and cross-cutting concerns.
359
360
**Key Areas:**
361
- **Spring Aspects**: AspectJ integration for advanced AOP
362
- **Spring Instrument**: Load-time weaving and instrumentation
363
- **Spring Context Support**: Additional context implementations
364
- **Spring WebSocket**: WebSocket support for real-time communication
365
- **Spring OXM**: Object/XML mapping abstractions
366
367
For comprehensive details: [Integration & Support](integration.md)
368
369
## Common Patterns
370
371
### Configuration Patterns
372
373
```java { .api }
374
// Java-based configuration
375
@Configuration
376
@EnableTransactionManagement
377
@ComponentScan(basePackages = {"com.example.service", "com.example.repository"})
378
public class AppConfig {
379
380
@Bean
381
@Profile("development")
382
public DataSource devDataSource() {
383
return new EmbeddedDatabaseBuilder()
384
.setType(EmbeddedDatabaseType.H2)
385
.build();
386
}
387
388
@Bean
389
@Profile("production")
390
public DataSource prodDataSource() {
391
HikariDataSource dataSource = new HikariDataSource();
392
dataSource.setJdbcUrl("jdbc:postgresql://localhost/mydb");
393
return dataSource;
394
}
395
}
396
```
397
398
### Dependency Injection Best Practices
399
400
```java { .api }
401
// Constructor injection (recommended)
402
@Service
403
public class OrderService {
404
405
private final PaymentService paymentService;
406
private final EmailService emailService;
407
408
public OrderService(PaymentService paymentService, EmailService emailService) {
409
this.paymentService = paymentService;
410
this.emailService = emailService;
411
}
412
}
413
414
// Qualifier for multiple implementations
415
@Service
416
public class NotificationService {
417
418
@Autowired
419
@Qualifier("emailNotifier")
420
private Notifier emailNotifier;
421
422
@Autowired
423
@Qualifier("smsNotifier")
424
private Notifier smsNotifier;
425
}
426
```
427
428
### Resource Management
429
430
```java { .api }
431
// Resource loading
432
@Service
433
public class ConfigurationService {
434
435
@Autowired
436
private ResourceLoader resourceLoader;
437
438
public Properties loadConfiguration(String configPath) {
439
try {
440
Resource resource = resourceLoader.getResource("classpath:" + configPath);
441
Properties props = new Properties();
442
props.load(resource.getInputStream());
443
return props;
444
} catch (IOException e) {
445
throw new ConfigurationException("Failed to load configuration", e);
446
}
447
}
448
}
449
```
450
451
## Module Dependencies
452
453
Understanding Spring's modular architecture helps in selecting the right dependencies:
454
455
- **spring-core + spring-beans**: Minimal IoC container
456
- **+ spring-context**: Full application context with events, validation, i18n
457
- **+ spring-aop**: Aspect-oriented programming support
458
- **+ spring-web**: Web application utilities
459
- **+ spring-webmvc**: Traditional MVC framework
460
- **+ spring-webflux**: Reactive web framework (alternative to webmvc)
461
- **+ spring-jdbc + spring-tx**: Data access and transaction management
462
- **+ spring-orm**: ORM integration (Hibernate, JPA)
463
- **+ spring-test**: Testing utilities and TestContext framework
464
465
For a complete Spring application, typically you'll need spring-context (which includes core and beans) plus specific modules for your use case (web, data access, etc.).