Mastering Spring Framework: Core Concepts, Modules, and Practical Guides
This comprehensive guide walks Java developers through Spring Framework’s essential features—including its modular architecture, dependency injection mechanisms, bean lifecycle, annotation‑based configuration, data‑access support, AOP concepts, and MVC workflow—providing clear explanations, code examples, and visual diagrams to deepen understanding.
1. General Overview
Spring Framework has become the de‑facto standard for Java web development. It is a lightweight, loosely‑coupled, open‑source application framework that offers a layered architecture, integrates with other technologies (Hibernate, EJB, etc.), and promotes POJO‑based programming.
Key Advantages
Selective component usage thanks to its layered design.
Supports POJO programming, enabling continuous integration and testability.
Dependency injection (DI) and inversion of control (IoC) simplify JDBC handling.
Free and open‑source.
Core Features
Lightweight core container.
IoC container for managing bean lifecycles.
Aspect‑Oriented Programming (AOP) for cross‑cutting concerns.
Comprehensive MVC web support.
Transaction management abstraction.
JDBC exception hierarchy for streamlined error handling.
Spring Modules
Spring is divided into several modules:
Core Container : Spring Core, Spring Bean, Spring Expression Language (SpEL), Spring Context.
Data Access / Integration : JDBC, ORM, OXM, JMS, Transaction.
Web : Web, Web‑Servlet, Web‑Socket, Web‑Portlet.
AOP
Instrumentation
Test
Miscellaneous : Messaging (STOMP), Aspects (AspectJ integration).
Configuration Files
Spring configuration is typically expressed in XML, which can become verbose in large projects.
2. Dependency Injection (IoC)
What is the Spring IoC Container?
The container creates, assembles, configures, and manages the full lifecycle of objects (beans) using dependency injection. Configuration metadata can be supplied via XML, Java annotations, or Java code.
Types of Dependency Injection
Constructor injection
Setter injection
Spring primarily supports constructor and setter injection.
Constructor vs. Setter Injection
Constructor injection: no partial injection, creates a new instance on any change, suited for many properties.
Setter injection: allows partial injection, does not create a new instance on change, suited for few properties.
IoC Containers
BeanFactory : Lazily creates beans on request.
ApplicationContext : Extends BeanFactory with eager loading, internationalization, and annotation support.
Benefits of IoC
Reduces code volume.
Improves testability by removing hard‑coded singletons.
Promotes loose coupling with minimal intrusion.
Supports eager and lazy bean instantiation.
Implementation Mechanism
Spring implements IoC using the Factory pattern combined with Java reflection.
interface Fruit { void eat(); }
class Apple implements Fruit { public void eat() { System.out.println("Apple"); } }
class Orange implements Fruit { public void eat() { System.out.println("Orange"); } }
class Factory {
public static Fruit getInstance(String className) {
Fruit f = null;
try { f = (Fruit) Class.forName(className).newInstance(); }
catch (Exception e) { e.printStackTrace(); }
return f;
}
}
class Client { public static void main(String[] a) { Fruit f = Factory.getInstance("io.github.dunwu.spring.Apple"); if (f != null) f.eat(); } }3. Beans
What Is a Spring Bean?
Objects that form the backbone of a Spring application.
Managed by the Spring IoC container (instantiated, configured, assembled, and destroyed).
Configuration Approaches
XML configuration (e.g.,
<bean id="studentbean" class="org.edureka.firstSpring.StudentBean">...).
Annotation‑based configuration using @Bean and @Configuration.
Java‑based API configuration with @Bean methods.
@Configuration
public class StudentConfig {
@Bean
public StudentBean myStudent() {
return new StudentBean();
}
}Bean Scopes
Singleton – one instance per container.
Prototype – a new instance each request.
Request – new instance per HTTP request (Web‑aware containers only).
Session – new instance per HTTP session (Web‑aware containers only).
Global‑session – similar to session but for portlet‑based applications.
Bean Lifecycle
Instantiation based on bean definition.
Dependency injection of properties.
Invocation of BeanNameAware methods.
Invocation of BeanFactoryAware methods.
Execution of BeanPostProcessor pre‑initialization methods.
Calling custom init method (if defined).
Execution of BeanPostProcessor post‑initialization methods.
Invocation of DisposableBean on container shutdown.
Calling custom destroy method (if defined).
Internal Beans
Beans defined inside another bean’s property or constructor‑arg are internal beans; they are always anonymous and prototype‑scoped.
public class Student { private Person person; /* getters/setters */ }
public class Person { private String name; private String address; /* getters/setters */ } <bean id="StudentBean" class="com.edureka.Student">
<property name="person">
<bean class="com.edureka.Person">
<property name="name" value="Scott"/>
<property name="address" value="Bangalore"/>
</bean>
</property>
</bean>4. Annotations
Annotation‑Based Container Configuration
Instead of XML, developers can place configuration directly on classes, methods, or fields using annotations such as @Component, @Controller, @Service, and @Repository. Annotation processing must be enabled with <context:annotation-config/> in the XML configuration.
Key Stereotype Annotations
@Component : Generic component, detected by classpath scanning.
@Controller : Marks a Spring MVC controller.
@Service : Indicates a service‑layer component.
@Repository : DAO component with exception translation.
@Required
Applied to a bean property setter to enforce that the property must be supplied either via explicit XML configuration or autowiring; otherwise a BeanInitializationException is thrown.
public class Employee {
private String name;
@Required
public void setName(String name) { this.name = name; }
public String getName() { return name; }
}@Autowired and @Qualifier
@Autowiredperforms type‑driven injection on constructors, setters, or fields. When multiple beans of the same type exist, @Qualifier("beanName") disambiguates which bean to inject.
public class Employee { private String name; @Autowired public void setName(String name) { this.name = name; } }
public class EmpAccount {
@Autowired @Qualifier("emp1") private Employee emp;
public void showName() { System.out.println("Employee name : " + emp.getName()); }
}@RequestMapping
Maps HTTP requests to controller classes or handler methods, specifying URL patterns and request methods.
5. Data Access
Spring DAO
Provides a consistent abstraction over various persistence technologies (JDBC, Hibernate, JPA, etc.), allowing easy switching and unified exception handling.
Supported JDBC Templates
JdbcTemplate
SimpleJdbcTemplate
NamedParameterJdbcTemplate
SimpleJdbcInsert
SimpleJdbcCall
Hibernate Access
Using HibernateTemplate with callbacks.
Extending HibernateDaoSupport and applying AOP interceptors.
Transaction Management
Programmatic transaction management (manual control).
Declarative transaction management (annotations or XML).
Supported ORM Frameworks
Hibernate
iBatis
JPA
JDO
OJB
6. AOP (Aspect‑Oriented Programming)
Fundamentals
AOP separates cross‑cutting concerns (e.g., logging, security) from core business logic. An aspect combines a pointcut (where to apply) and advice (what to do).
JoinPoint
A point during program execution, such as a method invocation; in Spring AOP, join points are always method executions.
Advice Types
Before : Runs before the method.
After Returning : Runs after successful execution.
After Throwing : Runs when an exception is thrown.
After (finally) : Runs after method completion regardless of outcome.
Around : Wraps the method execution.
Concern vs. Cross‑Cutting Concern
A concern is a module‑specific behavior, while a cross‑cutting concern affects multiple modules (e.g., logging, security).
Implementation Approaches
Static proxy (compile‑time weaving or class‑loader weaving).
Dynamic proxy (runtime): JDK dynamic proxies or CGLIB.
Spring AOP vs. AspectJ AOP
Spring AOP uses dynamic proxies; AspectJ uses static weaving.
Spring AOP supports method‑level pointcuts; AspectJ also supports field‑level pointcuts.
Proxy Concept
After applying advice, the resulting object is a proxy that delegates calls to the target bean.
Advice + Target Object = ProxyWeaving
Weaving links aspects with target objects; in Spring AOP, weaving occurs at runtime.
7. MVC (Model‑View‑Controller)
Purpose of Spring MVC
Provides a flexible, loosely‑coupled framework for building web applications using the MVC pattern, separating input, business, and view logic.
DispatcherServlet Workflow
Receives an HTTP request.
Uses HandlerMapping (configured in -servlet.xml) to locate the appropriate handler and interceptor chain.
Selects a suitable HandlerAdapter to invoke the handler (controller).
Extracts request data, performs type conversion, data binding, and validation.
Controller processes the request and returns a ModelAndView.
ViewResolver selects a view based on the model and renders the response.
WebApplicationContext
An extension of ApplicationContext that adds web‑specific features, such as theme resolution and servlet association.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
