Java Notes
Complete introduction to Spring Framework - IoC container, dependency injection, Spring modules, configuration, and why Spring became the standard for Java enterprise applications.
What is Spring Framework?
Spring is the most popular Java application framework that provides comprehensive infrastructure support for developing enterprise Java applications. It handles the plumbing of your application so you can focus on business logic.
Spring's core principle: Inversion of Control (IoC) — the framework manages object creation and wiring, not your code.
Spring Architecture — Module Overview
| Core | AOP | Data | Web | |||||
|---|---|---|---|---|---|---|---|---|
| Container | Aspects | Access | MVC | |||||
| - Beans | - AspectJ | - JDBC | - REST | |||||
| - Context | - Proxies | - ORM | - WebSocket | |||||
| - SpEL | - Advice | - JPA | - Servlet | |||||
| - IoC | - Logging | - TX | - Thymeleaf | |||||
| Security | Test | Messaging | Integration | |||||
| - AuthN | - JUnit | - JMS | - Scheduling | |||||
| - AuthZ | - Mockito | - AMQP | - Caching | |||||
| - OAuth2 | - MockMvc | - Kafka |
Core Concepts
1. Inversion of Control (IoC)
Traditional approach — YOU create dependencies:
// ❌ Tight coupling — hard to test, hard to change
public class OrderService {
private EmailService emailService = new EmailService(); // YOU create
private PaymentService paymentService = new PaymentService(); // YOU create
private OrderDAO orderDAO = new OrderDAO(); // YOU create
}Spring approach — CONTAINER creates and injects dependencies:
// ✅ Loose coupling — easy to test, easy to change
@Service
public class OrderService {
private final EmailService emailService; // Spring injects
private final PaymentService paymentService; // Spring injects
private final OrderDAO orderDAO; // Spring injects
@Autowired
public OrderService(EmailService emailService,
PaymentService paymentService,
OrderDAO orderDAO) {
this.emailService = emailService;
this.paymentService = paymentService;
this.orderDAO = orderDAO;
}
}2. Dependency Injection (DI)
DI is the mechanism through which IoC is achieved. Spring supports:
| Type | Annotation | Best For |
|---|---|---|
| Constructor Injection | @Autowired on constructor | Recommended — immutable, testable |
| Setter Injection | @Autowired on setter | Optional dependencies |
| Field Injection | @Autowired on field | Quick prototyping (not recommended) |
3. Spring Container (ApplicationContext)
The container is responsible for:
- Creating objects (beans)
- Configuring objects
- Assembling dependencies
- Managing lifecycle
// Creating Spring container
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// Getting beans from container
UserService userService = context.getBean(UserService.class);Spring Configuration Approaches
1. XML Configuration (Legacy)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userRepository" class="com.example.UserRepository" />
<bean id="userService" class="com.example.UserService">
<constructor-arg ref="userRepository" />
</bean>
</beans>2. Java Configuration (Modern)
@Configuration
@ComponentScan("com.example")
public class AppConfig {
@Bean
public DataSource dataSource() {
HikariDataSource ds = new HikariDataSource();
ds.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
ds.setUsername("root");
ds.setPassword("password");
return ds;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}3. Annotation Configuration (Most Common)
@Component // Generic Spring-managed bean
@Service // Business logic layer
@Repository // Data access layer
@Controller // Web controller (MVC)
@RestController // REST API controllerFirst Spring Application
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.4</version>
</dependency>
</dependencies>Model
public class Student {
private String name;
private String email;
// getters, setters, constructor
}Repository
@Repository
public class StudentRepository {
private List<Student> students = new ArrayList<>();
public void save(Student student) {
students.add(student);
}
public List<Student> findAll() {
return Collections.unmodifiableList(students);
}
}Service
@Service
public class StudentService {
private final StudentRepository repository;
@Autowired
public StudentService(StudentRepository repository) {
this.repository = repository;
}
public void registerStudent(String name, String email) {
Student student = new Student(name, email);
repository.save(student);
System.out.println("Student registered: " + name);
}
public List<Student> getAllStudents() {
return repository.findAll();
}
}Configuration
@Configuration
@ComponentScan("com.example")
public class AppConfig {
// Spring auto-discovers @Component, @Service, @Repository classes
}Main Application
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
StudentService service = context.getBean(StudentService.class);
service.registerStudent("Rahul", "rahul@example.com");
service.registerStudent("Priya", "priya@example.com");
System.out.println("All students: " + service.getAllStudents());
}
}Spring vs Spring Boot
| Feature | Spring Framework | Spring Boot |
|---|---|---|
| Configuration | Manual (XML/Java) | Auto-configuration |
| Server | External (Tomcat/Jetty) | Embedded server |
| Startup | Complex setup | @SpringBootApplication |
| Dependencies | Manual selection | Starter POMs |
| Production | Manual deployment | Fat JAR |
| Best for | Learning fundamentals | Building applications |
Spring Ecosystem
| Project | Purpose |
|---|---|
| Spring Boot | Quick application development |
| Spring MVC | Web applications and REST APIs |
| Spring Data | Database access (JPA, MongoDB, Redis) |
| Spring Security | Authentication and authorization |
| Spring Cloud | Microservices (Config, Discovery, Gateway) |
| Spring Batch | Batch processing |
| Spring Integration | Enterprise integration patterns |
Interview Key Points
- Spring is an IoC container that manages object lifecycle
- IoC means the container controls object creation, not your code
- DI is the mechanism to inject dependencies into beans
- Three DI types: Constructor (best), Setter, Field (avoid)
@Component= generic,@Service= business,@Repository= DAO,@Controller= web- ApplicationContext is the Spring IoC container
- Spring 6+ requires Java 17+ and uses
jakartanamespace - Spring Boot is NOT a replacement — it's built ON TOP of Spring Framework
Summary
In this chapter, we learned about Spring Framework Introduction in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Key Takeaways for Spring Introduction
- This topic is fundamental in Java development and is frequently asked in interviews
- Make sure to do hands-on practice for practical implementation
- Understanding its use in real-world projects is important for writing production-ready code
- Keep referring to documentation and official Java docs for the latest updates
- Also develop testing and debugging skills alongside this topic
- Follow industry best practices and actively participate in code reviews
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Spring Framework Introduction.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, spring, framework, introduction
Related Java Master Course Topics