Spring Framework & Spring Boot: Complete Notes



Table of Contents
Spring Framework & Spring Boot: Complete Notes
1. Introduction to Spring Framework
What is the Spring Framework?
Spring is an open-source, lightweight Java framework used to build enterprise-grade applications. It provides comprehensive infrastructure support so developers can focus on business logic rather than boilerplate code.
Core philosophy: "Don't call us, we'll call you" — the framework controls the flow (Inversion of Control).
Advantages of Spring
| Advantage | Description |
|---|---|
| Loose Coupling | Objects don't create their own dependencies; Spring wires them together |
| Inversion of Control (IoC) | The framework manages object creation and lifecycle |
| Dependency Injection (DI) | Dependencies are injected at runtime, not hardcoded |
| Modular Architecture | Use only the modules you need (Core, Web, Data, etc.) |
| Testability | DI makes unit testing easy by injecting mock objects |
| Scalability | Supports large enterprise apps and microservices |
| Integration | Works with Hibernate, JPA, Kafka, Redis, REST, SOAP, etc. |
Spring Module Overview
Spring Framework
│
├── Core Container
│ ├── spring-core → IoC and DI fundamentals
│ ├── spring-beans → BeanFactory, bean definitions
│ ├── spring-context → ApplicationContext, events
│ └── spring-expression → SpEL (Spring Expression Language)
│
├── AOP & Instrumentation
│ ├── spring-aop → Aspect-Oriented Programming
│ └── spring-aspects → AspectJ integration
│
├── Data Access / Integration
│ ├── spring-jdbc → JDBC template, exception handling
│ ├── spring-orm → JPA, Hibernate integration
│ ├── spring-tx → Transaction management
│ └── spring-messaging → JMS, Kafka, RabbitMQ
│
├── Web Layer
│ ├── spring-web → Core web support
│ ├── spring-webmvc → Spring MVC (DispatcherServlet)
│ └── spring-webflux → Reactive web (non-blocking)
│
└── Test
└── spring-test → MockMvc, @SpringBootTest, etc.
2. IoC (Inversion of Control) & DI (Dependency Injection)
IoC Container
The IoC Container is the heart of Spring. It:
- Creates objects (called Beans)
- Manages their lifecycle
- Wires dependencies between them
Two main IoC container types:
BeanFactory— basic, lazy loadingApplicationContext— advanced, eager loading (preferred)
Dependency Injection Types
1. Constructor Injection (Recommended)
@Component
public class OrderService {
private final PaymentService paymentService;
@Autowired // optional in modern Spring
public OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}
}
2. Setter Injection
@Component
public class OrderService {
private PaymentService paymentService;
@Autowired
public void setPaymentService(PaymentService paymentService) {
this.paymentService = paymentService;
}
}
3. Field Injection (Not recommended for production)
@Component
public class OrderService {
@Autowired
private PaymentService paymentService;
}
Best Practice: Use constructor injection — it supports immutability and makes dependencies explicit.
3. Spring Beans & Annotations
What is a Bean?
A Bean is any object managed by the Spring IoC container.
Stereotype Annotations
| Annotation | Use Case |
|---|---|
@Component | Generic Spring-managed component |
@Service | Business logic layer |
@Repository | Data access layer (DAO) |
@Controller | MVC web controller |
@RestController | REST API controller (@Controller + @ResponseBody) |
Bean Scopes
| Scope | Description |
|---|---|
singleton (default) | One instance per Spring container |
prototype | New instance every time it's requested |
request | One instance per HTTP request (Web only) |
session | One instance per HTTP session (Web only) |
@Component
@Scope("prototype")
public class TaskProcessor { }
Configuration with Java Class
@Configuration
public class AppConfig {
@Bean
public PaymentService paymentService() {
return new PaymentService();
}
}
4. Spring AOP (Aspect-Oriented Programming)
What is AOP?
AOP separates cross-cutting concerns (logging, security, transactions) from business logic.
Key Terms
| Term | Meaning |
|---|---|
| Aspect | The class containing cross-cutting logic |
| Advice | The action taken (before, after, around a method) |
| Join Point | A point in execution (e.g., method call) |
| Pointcut | Expression that selects join points |
| Weaving | Applying aspects to target objects |
Advice Types
@Aspect
@Component
public class LoggingAspect {
// Runs before method execution
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint jp) {
System.out.println("Before: " + jp.getSignature());
}
// Runs after method returns
@AfterReturning("execution(* com.example.service.*.*(..))")
public void logAfter() {
System.out.println("Method completed.");
}
// Wraps the method
@Around("execution(* com.example.service.*.*(..))")
public Object logAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("Start");
Object result = pjp.proceed();
System.out.println("End");
return result;
}
}
5. Introduction to Spring Boot
What is Spring Boot?
Spring Boot is a convention-over-configuration extension of Spring that makes it easy to create production-ready Spring applications with minimal setup.
Spring vs Spring Boot
| Feature | Spring | Spring Boot |
|---|---|---|
| Configuration | Manual XML / Java config | Auto-configuration |
| Server setup | External (Tomcat/Jetty) | Embedded server |
| Dependency management | Manual | Starter POMs |
| Boilerplate | High | Minimal |
| Production readiness | Manual setup | Built-in (Actuator) |
Spring Boot Key Features
- Auto-Configuration — Automatically configures beans based on classpath
- Starter Dependencies — Pre-packaged dependency groups
- Embedded Server — Tomcat/Jetty/Undertow built in
- Spring Actuator — Health checks, metrics, monitoring
- Spring Boot DevTools — Hot reload during development
- Externalized Configuration —
application.properties/application.yml
6. Spring Boot Project Structure
my-spring-app/ ├── src/ │ ├── main/ │ │ ├── java/com/example/myapp/ │ │ │ ├── MyAppApplication.java ← Entry point │ │ │ ├── controller/ │ │ │ │ └── UserController.java │ │ │ ├── service/ │ │ │ │ └── UserService.java │ │ │ ├── repository/ │ │ │ │ └── UserRepository.java │ │ │ └── model/ │ │ │ └── User.java │ │ └── resources/ │ │ ├── application.properties ← Config file │ │ └── static/ ← Static assets │ └── test/ │ └── java/com/example/myapp/ │ └── MyAppApplicationTests.java └── pom.xml ← Maven dependencies
7. Entry Point & Key Annotations
@SpringBootApplication // = @Configuration + @EnableAutoConfiguration + @ComponentScan
public class MyAppApplication {
public static void main(String[] args) {
SpringApplication.run(MyAppApplication.class, args);
}
}
Common Annotations Summary
| Annotation | Purpose |
|---|---|
@SpringBootApplication | Bootstraps the entire application |
@RestController | REST API controller |
@RequestMapping | Maps URL paths to methods |
@GetMapping / @PostMapping | HTTP method mappings |
@Autowired | Inject dependencies |
@Value | Inject values from properties file |
@Entity | JPA entity (database table) |
@Repository | Data access object |
@Service | Business logic bean |
@Transactional | Manage DB transactions |
@Configuration | Define beans in Java config |
@Bean | Declare a Spring bean manually |
8. Building a REST API with Spring Boot
Controller Example
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> getAllUsers() {
return userService.findAll();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.save(user);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.update(id, user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.delete(id);
}
}
application.properties
# Server server.port=8080 # Database (H2 in-memory example) spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true # App name spring.application.name=my-spring-app
9. Spring Data JPA
Entity
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and Setters
}
Repository
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
// Spring auto-generates: findAll(), findById(), save(), delete(), etc.
// Custom query by method name:
List<User> findByName(String name);
// Custom JPQL query:
@Query("SELECT u FROM User u WHERE u.email = :email")
Optional<User> findByEmail(@Param("email") String email);
}
Service
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> findAll() {
return userRepository.findAll();
}
public User findById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new RuntimeException("User not found"));
}
public User save(User user) {
return userRepository.save(user);
}
public void delete(Long id) {
userRepository.deleteById(id);
}
}
10. Spring Boot Starters (pom.xml)
<dependencies>
<!-- Web (REST API + Embedded Tomcat) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA + Hibernate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Actuator (Monitoring) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- H2 In-memory DB (for testing) -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- DevTools (hot reload) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
</dependencies>
11. Exception Handling
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Something went wrong");
}
}
12. Spring Security (Basics)
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
}
13. Spring Boot Actuator
Add the starter dependency, then access endpoints:
| Endpoint | Description |
|---|---|
/actuator/health | App health status |
/actuator/info | App info |
/actuator/metrics | Performance metrics |
/actuator/beans | All loaded beans |
/actuator/env | Environment properties |
Enable in application.properties:
management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always
14. Quick Reference — Request Mapping Annotations
| Annotation | HTTP Method | Use |
|---|---|---|
@GetMapping | GET | Fetch data |
@PostMapping | POST | Create resource |
@PutMapping | PUT | Update entire resource |
@PatchMapping | PATCH | Partial update |
@DeleteMapping | DELETE | Delete resource |
15. Learning Roadmap
Phase 1 — Spring Core ✅ IoC & DI ✅ Bean lifecycle & scopes ✅ Annotations Phase 2 — Spring Boot Basics ✅ Project setup (Spring Initializr) ✅ REST API creation ✅ application.properties config Phase 3 — Data Layer → Spring Data JPA → Hibernate ORM → MySQL / PostgreSQL integration Phase 4 — Security & Validation → Spring Security (JWT Auth) → Bean Validation (@Valid, @NotNull) Phase 5 — Advanced Topics → Spring AOP → Spring Cache → Spring Async → Spring Actuator + Monitoring Phase 6 — Microservices → Spring Cloud → Eureka (Service Discovery) → API Gateway → Feign Client → Config Server
Thanks for reading!