Unit IV Block 1: Spring Core Foundations
Lectures 25-28 - dependency injection, IoC, bean scope, and annotations
Block Overview
This block starts Unit IV with the core ideas that define Spring applications: inversion of control, dependency injection, lifecycle management, bean scopes, and annotation-driven wiring.
Course Outcome: CO-4 (K3-K4 - Application & Analysis)
Lectures Covered: 25-28
Theme: Spring Core basics
Lecture 25: Spring Core Basics & Dependency Injection
What is Spring?
- Popular Java framework for enterprise apps
- Provides DI, AOP, and MVC
- Lightweight and non-invasive
- Large ecosystem (Spring Boot, Spring Data, etc.)
Dependency Injection (DI)
Spring XML Configuration
Java Annotation Configuration
Using Spring
// XML-based
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
UserService service = context.getBean("userService", UserService.class);
// Annotation-based
ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
UserService service = context.getBean(UserService.class);Lecture 26: Spring IoC & Bean Life Cycle
Bean Lifecycle
Bean Scopes
@Bean
@Scope("singleton") // One instance per context
public UserService userServiceSingleton() {}
@Bean
@Scope("prototype") // New instance each time
public UserService userServicePrototype() {}
@Bean
@Scope("request") // One per HTTP request
public UserService userServiceRequest() {}
@Bean
@Scope("session") // One per HTTP session
public UserService userServiceSession() {}Autowiring
ApplicationContext
// Get bean
UserService service = context.getBean(UserService.class);
// Check if bean exists
boolean exists = context.containsBean("userService");
// Get all beans of type
Map<String, UserService> beans =
context.getBeansOfType(UserService.class);
// Listener support
context.addApplicationListener(event -> {
System.out.println("Event: " + event);
});Lecture 27: Bean Scopes: Singleton, Prototype, Request, Session, Application
Scope Summary
singleton: one bean per containerprototype: new bean each request to the containerrequest: one bean per HTTP requestsession: one bean per HTTP sessionapplication: one bean per servlet context
Why Scope Matters
- Controls shared state
- Helps avoid lifecycle bugs
- Decides whether a bean is safe to reuse broadly
Lecture 28: Autowiring & Annotations in Spring
Common Annotations
@Component@Service@Repository@Controller@Autowired@Qualifier@Primary
Example
Why This Matters
- Annotation-based configuration reduces XML boilerplate
- Constructor injection makes dependencies explicit and testable
Key Takeaways
- Spring manages object creation through the IoC container
- Dependency injection reduces tight coupling
- Bean scope and lifecycle affect correctness and performance
- Annotation-based configuration is central to modern Spring apps
Next Block
Unit IV continues with design patterns, AOP, and bean configuration styles.