Spring Framework Overview
Spring Framework is an open-source, lightweight Java development platform desgined to enhance development efficiency and system maintainability. It provides support for Inversion of Control (IoC) and Aspect-Oriented Programming (AOP), simplifies database access, integrates third-party components (email, scheduling, caching), and facilitates RESTful application development and unit testing.
Core Modules
The Core Container is the foundation of Spring, enabling IoC and dependency injection:
spring-core: Fundamental utility classes.spring-beans: Support for bean creation, configuration, and management.spring-context: Features like internationalization, event propagation, and resource loading.spring-expression: Expression language support, independent of other modules.
AOP Support
spring-aop: Core AOP implementation.spring-aspects: Integration with AspectJ.spring-instrument: JVM agent support for class weaving (e.g., Tomcat).
Data Access & Integration
spring-jdbc: Abstract JDBC layer.spring-tx: Transaction management.spring-orm: Integration with Hibernate, JPA, iBatis.spring-oxm: Object-to-XML mapping (JAXB, XStream, etc.).spring-jms: Messaging support.
Web & Reactive
spring-web: Basic web utilities.spring-webmvc: Model-View-Controller implementation.spring-websocket: Bidirectional WebSocket communication.spring-webflux: Non-blocking, reactive web stack (no Servlet API required).
Testing
The spring-test module supports Test-Driven Development (TDD) with integrations for JUnit, TestNG, Mockito, and PowerMock.
Relationship Between Spring, Spring MVC, and Spring Boot
- Spring provides the core infrastructure, especially the
spring-coremodule. - Spring MVC is a module within Spring for building web applications using the MVC pattern (Model, View, Controller).
- Spring Boot simplifies configuration by reducing boilerplate XML/Java setup. It auto-configures Spring MVC (and other modules) for rapid development.
Inversion of Control (IoC)
IoC is a design principle where the control of object creation and lifecycle management is transferred to the Spring container rather than being handled programmatically.
Bean Definition
Objects managed by the IoC container are called Beans. Configuration metadata tells the container which objects to manage.
XML configuration example:
<bean id="notificationService" class="com.example.NotificationService">
<constructor-arg value="email"/>
</bean>
Stereotype Annotations
@Component: Generic stereotype for any Spring-managed component.@Repository: Persistence layer (DAO).@Service: Service layer (business logic).@Controller: Spring MVC controller layer.
@Component vs @Bean
@Componentis used on classes and detected via classpath scanning (@ComponentScan).@Beanis used on methods, typically within@Configurationclasses, offering more explicit control over bean instantiation.
@Bean example:
@Configuration
public class AppConfig {
@Bean
public PaymentProcessor paymentProcessor() {
return new StripePaymentProcessor();
}
}
Conditional bean creation example (not possible with @Component):
@Bean
public NotificationService getNotificationService(String type) {
switch (type) {
case "SMS": return new SmsNotificationService();
case "EMAIL": return new EmailNotificationService();
default: return new PushNotificationService();
}
}
Dependency Injection Annotations
@Autowired(Spring): Defaults tobyType. If multiple beans of the same type exist, it falls back tobyName(field name or@Qualifier).@Resource(JDK): Defaults tobyName. Can also specifytypeor bothnameandtype.
Example of @Autowired with @Qualifier:
public class OrderService {
@Autowired
@Qualifier("smsSender")
private MessageSender sender;
}
Example of @Resource:
public class OrderService {
@Resource(name = "emailSender")
private MessageSender sender;
}
Bean Scopes
| Scope | Description |
|---|---|
singleton |
Single instance per IoC container (default). |
prototype |
New instance every time it is requested. |
request |
One instance per HTTP request (web only). |
session |
One instance per HTTP session (web only). |
application |
One instance per ServletContext (web only). |
websocket |
One instance per WebSocket session (web only). |
Annotation configuration:
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Task taskPrototype() {
return new Task();
}
Thread Safety in Singleton Beans
Singleton beans are thread-safe only if they are stateless. For stateful beans, avoid instance variables or use ThreadLocal to isolate state per thread.
Bean Lifecycle
- Container reads bean definitions.
- Instance created via reflection.
- Properties set via setters.
Awareinterfaces called (BeanNameAware,BeanFactoryAware, etc.).BeanPostProcessor.postProcessBeforeInitialization()runs.InitializingBean.afterPropertiesSet()or custominit-methodruns.BeanPostProcessor.postProcessAfterInitialization()runs.- On shutdown:
DisposableBean.destroy()or customdestroy-methodruns.
Aspect-Oriented Programming (AOP)
AOP encapsulates cross-cutting concerns (logging, transactions, security) to reduce duplication and decouple modules.
Implementation
- Spring AOP: Runtime proxy-based (JDK dynamic proxy for interfaces, CGLIB for classes).
- AspectJ: Compile-time or load-time bytecode weaving, more powerful but complex.
Advice Types
- Before: Runs before the method.
- After: Runs after the method (regardless of outcome).
- AfterReturning: Runs after successful return.
- AfterThrowing: Runs if an exception is thrown.
- Around: Wraps the method call completely (can skip or modify execution).
Aspect Ordering
Control execution order with @Order or by implementing Ordered:
@Aspect
@Order(1)
@Component
public class MonitoringAspect {
// ...
}
@Aspect
@Component
public class SecurityAspect implements Ordered {
@Override
public int getOrder() {
return 2;
}
}