Prakhar Singh

Spring Framework & Spring Boot: Complete Notes

Cover Image for Spring Framework & Spring Boot: Complete Notes
Prakhar Singh
Prakhar Singh

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

AdvantageDescription
Loose CouplingObjects 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 ArchitectureUse only the modules you need (Core, Web, Data, etc.)
TestabilityDI makes unit testing easy by injecting mock objects
ScalabilitySupports large enterprise apps and microservices
IntegrationWorks with Hibernate, JPA, Kafka, Redis, REST, SOAP, etc.

Spring Module Overview

text
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 loading
  • ApplicationContext — advanced, eager loading (preferred)

Dependency Injection Types

java
@Component
public class OrderService {
    private final PaymentService paymentService;

    @Autowired  // optional in modern Spring
    public OrderService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }
}

2. Setter Injection

java
@Component
public class OrderService {
    private PaymentService paymentService;

    @Autowired
    public void setPaymentService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }
}
java
@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

AnnotationUse Case
@ComponentGeneric Spring-managed component
@ServiceBusiness logic layer
@RepositoryData access layer (DAO)
@ControllerMVC web controller
@RestControllerREST API controller (@Controller + @ResponseBody)

Bean Scopes

ScopeDescription
singleton (default)One instance per Spring container
prototypeNew instance every time it's requested
requestOne instance per HTTP request (Web only)
sessionOne instance per HTTP session (Web only)
java
@Component
@Scope("prototype")
public class TaskProcessor { }

Configuration with Java Class

java
@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

TermMeaning
AspectThe class containing cross-cutting logic
AdviceThe action taken (before, after, around a method)
Join PointA point in execution (e.g., method call)
PointcutExpression that selects join points
WeavingApplying aspects to target objects

Advice Types

java
@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

FeatureSpringSpring Boot
ConfigurationManual XML / Java configAuto-configuration
Server setupExternal (Tomcat/Jetty)Embedded server
Dependency managementManualStarter POMs
BoilerplateHighMinimal
Production readinessManual setupBuilt-in (Actuator)

Spring Boot Key Features

  1. Auto-Configuration — Automatically configures beans based on classpath
  2. Starter Dependencies — Pre-packaged dependency groups
  3. Embedded Server — Tomcat/Jetty/Undertow built in
  4. Spring Actuator — Health checks, metrics, monitoring
  5. Spring Boot DevTools — Hot reload during development
  6. Externalized Configuration — application.properties / application.yml

6. Spring Boot Project Structure

text
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

java
@SpringBootApplication   // = @Configuration + @EnableAutoConfiguration + @ComponentScan
public class MyAppApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyAppApplication.class, args);
    }
}

Common Annotations Summary

AnnotationPurpose
@SpringBootApplicationBootstraps the entire application
@RestControllerREST API controller
@RequestMappingMaps URL paths to methods
@GetMapping / @PostMappingHTTP method mappings
@AutowiredInject dependencies
@ValueInject values from properties file
@EntityJPA entity (database table)
@RepositoryData access object
@ServiceBusiness logic bean
@TransactionalManage DB transactions
@ConfigurationDefine beans in Java config
@BeanDeclare a Spring bean manually

8. Building a REST API with Spring Boot

Controller Example

java
@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

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

java
@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

java
@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

java
@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)

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

java
@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)

java
@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:

EndpointDescription
/actuator/healthApp health status
/actuator/infoApp info
/actuator/metricsPerformance metrics
/actuator/beansAll loaded beans
/actuator/envEnvironment properties

Enable in application.properties:

properties
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

14. Quick Reference — Request Mapping Annotations

AnnotationHTTP MethodUse
@GetMappingGETFetch data
@PostMappingPOSTCreate resource
@PutMappingPUTUpdate entire resource
@PatchMappingPATCHPartial update
@DeleteMappingDELETEDelete resource

15. Learning Roadmap

text
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!