PadhaikoAll subjects

Spring Boot and Modern Web Development (part 1: 4.1–4.2)

Java Programming (ENCT 327)

Open in the Padhaiko app

4.1 Spring Boot fundamentals; Dependency injection and inversion of control; Creating RESTful APIs with Spring Boot

Traditional Spring Framework applications required extensive XML or Java configuration to wire servlets, Jackson converters, data sources, and application servers manually. Spring Boot eliminates that boilerplate through convention over configuration, starter dependencies, auto-configuration, and an embedded web server (Tomcat by default), allowing developers to package and run production web services as a single executable JAR (java -jar app.jar).

Spring Boot Fundamentals

Inversion of Control (IoC) and Dependency Injection (DI)

Definition

Inversion of Control (IoC) and Dependency Injection (DI)

AspectConstructor InjectionField Injection (@Autowired)
ImmutabilityDependencies can be declared private finalFields cannot be final; mutable after creation
Null SafetyObject cannot exist without required dependenciesEasy to construct half-initialized objects in unit tests
Unit TestingPlain new OrderService(mockRepo) without SpringRequires reflection or full Spring test context
Circular DependenciesFails fast at startup with clear errorHides tight coupling and design flaws
Syntax Note@Autowired is optional on single-constructor classesRequires @Autowired on every field

Creating RESTful APIs with Spring Boot

In Spring Web MVC, a @RestController combines @Controller and @ResponseBody, automatically serializing returned Java objects/records to JSON via Jackson and deserializing incoming JSON request bodies.

Core Spring MVC Mapping and Parameter Annotations
AnnotationRoleExample Usage
@RestControllerMarks class as REST endpoint controller@RestController @RequestMapping("/api/courses")
@GetMapping / @PostMappingMaps HTTP GET / POST requests@GetMapping("/{id}"), @PostMapping
@PutMapping / @DeleteMappingMaps HTTP PUT (update) / DELETE requests@DeleteMapping("/{id}")
@PathVariableExtracts URI path segmentgetById(@PathVariable Long id)
@RequestParamExtracts query string parametersearch(@RequestParam(defaultValue="0") int page)
@RequestBodyBinds JSON request body to DTO/recordcreate(@RequestBody CourseRequest req)
ResponseEntity<T>Controls HTTP status code, headers, and bodyResponseEntity.status(HttpStatus.CREATED).body(saved)
Java
package edu.ioe.app.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

record CourseDto(Long id, String code, String title) {}

@RestController
@RequestMapping("/api/courses")
public class CourseController {
    private final CourseService courseService;

    // Constructor injection (single constructor -> @Autowired implied)
    public CourseController(CourseService courseService) {
        this.courseService = courseService;
    }

    @GetMapping
    public List<CourseDto> listAll(@RequestParam(required = false) String dept) {
        return courseService.findCourses(dept);
    }

    @GetMapping("/{id}")
    public ResponseEntity<CourseDto> getOne(@PathVariable Long id) {
        return ResponseEntity.ok(courseService.findById(id));
    }

    @PostMapping
    public ResponseEntity<CourseDto> create(@RequestBody CourseDto body) {
        CourseDto created = courseService.create(body);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }
}

4.2 Data Access with Spring

Enterprise applications follow a clean three-tier separation: Controller (HTTP/validation) -> Service (business rules & transaction boundaries) -> Repository (database persistence).

4.2.1 Overview of ORM and JPA

Relational databases store flat rows and foreign-key joins, whereas Java models rich object graphs with references and inheritance—a mismatch known as the Object-Relational Impedance Mismatch.

Definition

ORM, JPA, and Hibernate

Core JPA Mapping Annotations

4.2.2 Building a repository layer with spring data JPA

Instead of writing repetitive JDBC boilerplate or EntityManager queries for every table, Spring Data JPA generates complete repository implementations at startup from simple Java interfaces extending JpaRepository<T, ID>:

Java
package edu.ioe.app.model;

import jakarta.persistence.*;

@Entity
@Table(name = "students")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String rollNo;

    @Column(nullable = false)
    private String fullName;

    private String department;
    private double gpa;

    protected Student() {} // required by JPA

    public Student(String rollNo, String fullName, String department, double gpa) {
        this.rollNo = rollNo;
        this.fullName = fullName;
        this.department = department;
        this.gpa = gpa;
    }

    public Long getId() { return id; }
    public String getRollNo() { return rollNo; }
    public String getFullName() { return fullName; }
    public String getDepartment() { return department; }
    public double getGpa() { return gpa; }
    public void setGpa(double gpa) { this.gpa = gpa; }
}
Java
package edu.ioe.app.repository;

import edu.ioe.app.model.Student;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Optional;

public interface StudentRepository extends JpaRepository<Student, Long> {
    // 1. Derived query method: Spring parses the method name into SQL
    Optional<Student> findByRollNo(String rollNo);
    List<Student> findByDepartmentAndGpaGreaterThanEqual(String department, double minGpa);
    Page<Student> findByDepartment(String department, Pageable pageable);

    // 2. Custom JPQL query (references entity class/field names, not SQL table names)
    @Query("SELECT s FROM Student s WHERE s.gpa >= :threshold ORDER BY s.gpa DESC")
    List<Student> findHonorStudents(@Param("threshold") double threshold);
}

4.2.3 CRUD operations and transactional management

JpaRepository provides built-in CRUD (save, findById, findAll, existsById, deleteById) plus pagination (findAll(Pageable)). Business methods in the @Service layer coordinate multiple repository calls inside an atomic transaction using @Transactional.

Java
package edu.ioe.app.service;

import edu.ioe.app.model.Student;
import edu.ioe.app.repository.StudentRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StudentService {
    private final StudentRepository repo;

    public StudentService(StudentRepository repo) {
        this.repo = repo;
    }

    @Transactional
    public Student registerStudent(Student student) {
        if (repo.findByRollNo(student.getRollNo()).isPresent()) {
            throw new IllegalArgumentException("Duplicate roll number: " + student.getRollNo());
        }
        return repo.save(student);
    }

    @Transactional(readOnly = true)
    public Student getStudent(Long id) {
        return repo.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Student not found: " + id));
    }

    @Transactional
    public Student updateGpa(Long id, double newGpa) {
        Student s = getStudent(id);
        s.setGpa(newGpa); // Hibernate dirty checking auto-flushes UPDATE on commit
        return s;
    }

    @Transactional
    public void removeStudent(Long id) {
        repo.deleteById(id);
    }
}

Worked Examples

Example 4.1

4.1

A Spring Data JPA endpoint exposes GET /api/students?page=P&size=12 backed by studentRepository.findAll(PageRequest.of(P, 12)). Suppose the students table currently contains 53 rows.

  1. What is totalPages returned inside Spring Data's Page<Student>?
  2. How many elements are returned for P = 0, P = 4, and P = 5 (0-indexed pages)?
  3. What boolean values do hasNext() and isLast() return on P = 4?

Compute total pages using ceiling division (ceil(totalElements / pageSize)): totalPages = ceil(53 / 12) = 5 pages (valid 0-based page indices are 0, 1, 2, 3, 4).

Trace each requested page index:

  • P = 0: rows 1..12 -> 12 elements (hasNext() = true, isLast() = false).
  • Pages 0, 1, 2, 3 hold 4 * 12 = 48 rows.
  • P = 4: remaining rows 53 - 48 = 5 elements (rows 49..53).
  • P = 5: out of bounds -> 0 elements (empty List, though totalElements remains 53 and totalPages remains 5).

Check navigation metadata for P = 4 (the 5th and final page): Because P = 4 == totalPages - 1, hasNext() is false and isLast() is true.

Answer:

totalPages is 5. Page 0 returns 12 elements, page 4 returns 5 elements, and page 5 returns 0 elements. On page 4, hasNext() is false and isLast() is true.

Example 4.2

4.2

A @Service class defines a @Transactional method enroll(Long studentId, Long courseId) that performs two JPA updates:

  1. Decrements course.availableSeats by 1 (initially 10) and calls courseRepo.save(course).
  2. Inserts an Enrollment record via enrollRepo.save(...), which fails by throwing:
    • Case A: an unchecked IllegalStateException("Already enrolled"), or
    • Case B: a checked DuplicateEnrollmentException extends Exception (without rollbackFor configured).

What value does course.availableSeats hold in the database after enroll(...) exits in Case A and Case B?

Apply Spring's default @Transactional rollback policy:

  • By default, @Transactional rolls back only on unchecked exceptions (RuntimeException and Error), and commits when a checked exception (Exception not extending RuntimeException) is thrown unless rollbackFor = Exception.class is explicitly added.

Evaluate both cases:

  • Case A (IllegalStateException, unchecked): The AOP transaction proxy intercepts the RuntimeException, invokes rollback(), and discards step 1's SQL UPDATE. availableSeats remains 10.
  • Case B (checked Exception without rollbackFor): The proxy does not roll back by default; it commits step 1's UPDATE before propagating the exception! availableSeats becomes 10 - 1 = 9 (a data inconsistency bug unless @Transactional(rollbackFor = Exception.class) is added).
Answer:

In Case A, Spring rolls back the transaction and availableSeats stays 10. In Case B, Spring's default policy does not roll back checked exceptions, leaving availableSeats committed at 9 unless rollbackFor = Exception.class is specified.

Example 4.3

4.3

How should a student answer the past exam question: "Explain Inversion of Control (IoC) and Dependency Injection (DI) in Spring Boot, and compare Constructor Injection vs. Field Injection"?

Define IoC and DI Precisely:

  1. State that IoC transfers object creation and lifecycle control from application code (new) to Spring's ApplicationContext container, which manages Beans (@Component, @Service, @Repository).
  2. State that DI is how the container injects collaborator beans into dependent classes.

Show Minimal Constructor Injection Code and Compare: Write a 6-line @Service class receiving private final StudentRepository repo; through its constructor, then contrast Constructor Injection (final immutability, plain-Java unit testing, fail-fast on circular dependencies) against @Autowired field injection (mutable, requires reflection/Spring context in tests).

Answer:

A complete exam answer defines IoC (ApplicationContext managing bean lifecycles) and DI (container supplying collaborators), gives a clean @Service constructor-injection snippet with a final dependency field, and compares constructor injection favorably against @Autowired field injection on immutability, testability, and null safety.


Exercises

Practice Exercises — Spring Boot Fundamentals & Data Access

Question 1

What three annotations are combined inside @SpringBootApplication, and how do Spring Boot Starters and Auto-Configuration reduce setup compared to classic Spring?

The Three Meta-Annotations:

  1. @SpringBootConfiguration: Marks the main class as a Spring configuration class (@Bean factory).
  2. @EnableAutoConfiguration: Inspects JARs on the classpath and automatically registers sensible default beans (e.g., DispatcherServlet, Jackson ObjectMapper, DataSource, EntityManagerFactory).
  3. @ComponentScan: Scans the main class's package and sub-packages to discover @Component, @Service, @Repository, and @RestController beans.

Role of Starters and Auto-Configuration: Instead of manually hunting compatible dependency versions and writing verbose XML/Java config for Tomcat, Jackson, and Hibernate, adding a single starter (like spring-boot-starter-web or spring-boot-starter-data-jpa) pulls aligned libraries and triggers auto-configuration automatically.

Answer:

@SpringBootApplication combines @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan. Starters bundle compatible dependency trees, while auto-configuration inspects the classpath to wire server, JSON, and database beans automatically.

Question 2

Explain Inversion of Control (IoC) and Dependency Injection (DI), and state three reasons why Constructor Injection is preferred over @Autowired Field Injection in Spring Boot.

IoC and DI Concepts: Inversion of Control delegates bean instantiation and wiring to Spring's ApplicationContext rather than calling new inside business classes. Dependency Injection is the mechanism by which the container passes required collaborators into a bean.

Three Advantages of Constructor Injection:

  1. Immutability: Collaborator fields can be marked private final, guaranteeing they cannot be reassigned after construction.
  2. Easy Unit Testing: Tests can instantiate the service directly via new OrderService(mockRepo) without booting Spring or using reflection.
  3. Guaranteed Valid State & Fail-Fast: Required dependencies cannot be null, and circular dependencies are caught immediately at application startup.
Answer:

IoC delegates object lifecycle management to the Spring ApplicationContext, while DI injects required collaborator beans. Constructor injection is preferred because it allows final immutable fields, supports framework-free unit testing, and prevents NullPointerException or hidden circular dependencies.

Question 3

Write a Spring Boot @RestController for /api/books supporting:

  1. GET /api/books/{id} returning ResponseEntity<Book> using @PathVariable,
  2. GET /api/books?author=... filtering by optional @RequestParam, and
  3. POST /api/books accepting a JSON @RequestBody and returning HTTP 201 Created.

REST Controller Implementation:

Java
@RestController
@RequestMapping("/api/books")
public class BookController {
    private final BookService bookService;

    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping("/{id}")
    public ResponseEntity<Book> getBook(@PathVariable Long id) {
        return ResponseEntity.ok(bookService.findById(id));
    }

    @GetMapping
    public List<Book> listBooks(@RequestParam(required = false) String author) {
        return (author == null) ? bookService.findAll() : bookService.findByAuthor(author);
    }

    @PostMapping
    public ResponseEntity<Book> createBook(@RequestBody Book book) {
        Book saved = bookService.save(book);
        return ResponseEntity.status(HttpStatus.CREATED).body(saved);
    }
}

Annotation Roles Verified: @PathVariable extracts {id} from the URL path, @RequestParam(required = false) reads optional query parameters, @RequestBody deserializes JSON via Jackson, and ResponseEntity.status(HttpStatus.CREATED) returns status code 201.

Answer:

Annotate the class with @RestController and @RequestMapping("/api/books"), inject BookService via constructor, and implement @GetMapping("/{id}") (@PathVariable), @GetMapping (@RequestParam(required = false)), and @PostMapping (@RequestBody returning ResponseEntity.status(HttpStatus.CREATED)).

Question 4

Differentiate between JPA and Hibernate, and explain what a Spring Data JPA derived query method is. If a BookRepository extends JpaRepository<Book, Long> queries a table of 137 books with PageRequest.of(page, 15):

  1. How many total pages exist (getTotalPages())?
  2. How many books appear on the final valid page (index 9)?

JPA vs. Hibernate and Derived Queries:

  • JPA (Jakarta Persistence API) is the standard specification (interfaces and annotations like @Entity, @Id, EntityManager), while Hibernate is the concrete ORM engine implementing JPA and generating SQL.
  • Derived Query Methods let developers declare repository method signatures such as List<Book> findByAuthorAndPriceLessThan(String author, double maxPrice); and Spring Data JPA automatically parses the method name to generate the query.

Pagination Calculation (137 rows, page size 15):

  • totalPages = ceil(137 / 15): since 9 * 15 = 135 and 2 rows remain, totalPages = 10 (0-indexed pages 0 through 9).
  • Elements on final page (page = 9): 137 - 135 = 2 books.
Answer:

JPA is the persistence specification while Hibernate is its ORM implementation; derived query methods generate queries automatically from JpaRepository method names. For 137 books at 15 per page, getTotalPages() is 10 (indices 0..9) and page 9 contains 2 books.

Question 5

Explain how @Transactional manages database transactions in Spring Boot. What is Hibernate dirty checking, and why does calling a @Transactional method from another method inside the same class fail to start a new transaction?

@Transactional and Dirty Checking:

  • @Transactional wraps the bean in a Spring AOP proxy that opens a transaction before the method runs, commits on clean return, and rolls back automatically on unchecked exceptions (RuntimeException / Error).
  • Dirty checking: Within an active transaction, Hibernate tracks snapshots of loaded managed @Entity objects in the Persistence Context. Modifying an entity via a setter (e.g., student.setGpa(3.85)) automatically triggers an UPDATE SQL statement before commit without needing an explicit save() call.

The Self-Invocation Trap: Spring AOP proxies intercept only external calls arriving through the proxy reference. When methodA() calls this.methodB() inside the same class, the call goes directly to the raw target object (this), bypassing the proxy and skipping @Transactional behavior on methodB().

Answer:

Spring implements @Transactional via an AOP proxy that opens, commits, or rolls back transactions around method calls, while Hibernate dirty checking automatically flushes field changes on managed entities at commit. Self-invocation (this.otherMethod()) bypasses the AOP proxy, so @Transactional on the internal method is not applied.

← Database and Web CommunicationSpring Boot and Modern Web Development (part 2: 4.3–4.4) →