Spring Boot and Modern Web Development (part 1: 4.1–4.2)
Open in the Padhaiko app4.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
@SpringBootApplication: Entry-point meta-annotation combining three annotations:@SpringBootConfiguration(marks the class as a source of@Beandefinitions).@EnableAutoConfiguration(inspects the classpath—e.g., seeing PostgreSQL driver +spring-boot-starter-data-jpaautomatically configures aDataSourceandEntityManagerFactory).@ComponentScan(scans the current package and all sub-packages for Spring components).
- Starter POMs: Curated dependency bundles with tested compatible versions, such as
spring-boot-starter-web(Spring MVC + Jackson + Tomcat),spring-boot-starter-data-jpa(Hibernate + Spring Data), andspring-boot-starter-security. - Externalized Configuration:
src/main/resources/application.propertiesorapplication.ymlconfigures server port, database URL, and logging without recompiling code.
Inversion of Control (IoC) and Dependency Injection (DI)
Inversion of Control (IoC) and Dependency Injection (DI)
- Inversion of Control (IoC): A design principle in which object creation, wiring, and lifecycle management are handed over from application code to an external IoC Container (
ApplicationContext). Objects managed by the container are called Spring Beans. - Dependency Injection (DI): The specific pattern used by the IoC container to supply a bean's required collaborators (dependencies) at construction or initialization time rather than having the bean instantiate them with
new. - Stereotype Annotations:
@Component(generic bean),@Service(business logic),@Repository(data access + database exception translation), and@RestController(HTTP JSON endpoints). - Common Bean Scopes:
singleton(default—one shared instance perApplicationContext),prototype(new instance on every request to container), and web scopes (request,session).
| Aspect | Constructor Injection | Field Injection (@Autowired) |
|---|---|---|
| Immutability | Dependencies can be declared private final | Fields cannot be final; mutable after creation |
| Null Safety | Object cannot exist without required dependencies | Easy to construct half-initialized objects in unit tests |
| Unit Testing | Plain new OrderService(mockRepo) without Spring | Requires reflection or full Spring test context |
| Circular Dependencies | Fails fast at startup with clear error | Hides tight coupling and design flaws |
| Syntax Note | @Autowired is optional on single-constructor classes | Requires @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.
| Annotation | Role | Example Usage |
|---|---|---|
@RestController | Marks class as REST endpoint controller | @RestController @RequestMapping("/api/courses") |
@GetMapping / @PostMapping | Maps HTTP GET / POST requests | @GetMapping("/{id}"), @PostMapping |
@PutMapping / @DeleteMapping | Maps HTTP PUT (update) / DELETE requests | @DeleteMapping("/{id}") |
@PathVariable | Extracts URI path segment | getById(@PathVariable Long id) |
@RequestParam | Extracts query string parameter | search(@RequestParam(defaultValue="0") int page) |
@RequestBody | Binds JSON request body to DTO/record | create(@RequestBody CourseRequest req) |
ResponseEntity<T> | Controls HTTP status code, headers, and body | ResponseEntity.status(HttpStatus.CREATED).body(saved) |
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.
ORM, JPA, and Hibernate
- ORM (Object-Relational Mapping): A programming technique that maps Java classes to database tables, fields to columns, and object references to foreign keys, generating SQL automatically.
- JPA (Jakarta Persistence API): The standard Java specification (
jakarta.persistence.*) defining annotations (@Entity,@Id,@OneToMany) and theEntityManagerAPI. JPA itself is only an interface specification. - Hibernate ORM: The default JPA implementation bundled with
spring-boot-starter-data-jpa, responsible for generating dialect-specific SQL, managing the Persistence Context (first-level cache), and performing dirty checking (automatically issuingUPDATESQL if a managed entity's fields change inside a transaction).
Core JPA Mapping Annotations
@Entityand@Table(name = "students"): Maps a Java class to a database table (requires aprotected/publicno-arg constructor).@Idand@GeneratedValue(strategy = GenerationType.IDENTITY): Marks primary key and auto-increment strategy.@Column(nullable = false, unique = true, length = 120): Configures column constraints.- Associations:
@ManyToOne(e.g., manyStudents belong to oneDepartment),@OneToMany(mappedBy = "department"),@OneToOne, and@ManyToMany. Default fetch types:EAGERfor@ManyToOne/@OneToOne,LAZYfor@OneToMany/@ManyToMany(preferFetchType.LAZYto avoid N+1 query storms).
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>:
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; }
}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.
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
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.
- What is
totalPagesreturned inside Spring Data'sPage<Student>? - How many elements are returned for
P = 0,P = 4, andP = 5(0-indexed pages)? - What boolean values do
hasNext()andisLast()return onP = 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: rows1..12-> 12 elements (hasNext() = true,isLast() = false).- Pages
0, 1, 2, 3hold4 * 12 = 48rows. P = 4: remaining rows53 - 48 = 5elements (rows49..53).P = 5: out of bounds -> 0 elements (emptyList, thoughtotalElementsremains53andtotalPagesremains5).
Check navigation metadata for P = 4 (the 5th and final page): Because P = 4 == totalPages - 1, hasNext() is false and isLast() is true.
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.
4.2
A @Service class defines a @Transactional method enroll(Long studentId, Long courseId) that performs two JPA updates:
- Decrements
course.availableSeatsby1(initially10) and callscourseRepo.save(course). - Inserts an
Enrollmentrecord viaenrollRepo.save(...), which fails by throwing:- Case A: an unchecked
IllegalStateException("Already enrolled"), or - Case B: a checked
DuplicateEnrollmentException extends Exception(withoutrollbackForconfigured).
- Case A: an unchecked
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,
@Transactionalrolls back only on unchecked exceptions (RuntimeExceptionandError), and commits when a checked exception (Exceptionnot extendingRuntimeException) is thrown unlessrollbackFor = Exception.classis explicitly added.
Evaluate both cases:
- Case A (
IllegalStateException, unchecked): The AOP transaction proxy intercepts theRuntimeException, invokesrollback(), and discards step 1's SQLUPDATE.availableSeatsremains 10. - Case B (checked
ExceptionwithoutrollbackFor): The proxy does not roll back by default; it commits step 1'sUPDATEbefore propagating the exception!availableSeatsbecomes10 - 1 = 9(a data inconsistency bug unless@Transactional(rollbackFor = Exception.class)is added).
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.
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:
- State that IoC transfers object creation and lifecycle control from application code (
new) to Spring'sApplicationContextcontainer, which manages Beans (@Component,@Service,@Repository). - 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).
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
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:
@SpringBootConfiguration: Marks the main class as a Spring configuration class (@Beanfactory).@EnableAutoConfiguration: Inspects JARs on the classpath and automatically registers sensible default beans (e.g.,DispatcherServlet, JacksonObjectMapper,DataSource,EntityManagerFactory).@ComponentScan: Scans the main class's package and sub-packages to discover@Component,@Service,@Repository, and@RestControllerbeans.
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.
@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.
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:
- Immutability: Collaborator fields can be marked
private final, guaranteeing they cannot be reassigned after construction. - Easy Unit Testing: Tests can instantiate the service directly via
new OrderService(mockRepo)without booting Spring or using reflection. - Guaranteed Valid State & Fail-Fast: Required dependencies cannot be
null, and circular dependencies are caught immediately at application startup.
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.
Write a Spring Boot @RestController for /api/books supporting:
GET /api/books/{id}returningResponseEntity<Book>using@PathVariable,GET /api/books?author=...filtering by optional@RequestParam, andPOST /api/booksaccepting a JSON@RequestBodyand returning HTTP201 Created.
REST Controller Implementation:
@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.
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)).
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):
- How many total pages exist (
getTotalPages())? - 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): since9 * 15 = 135and2rows remain,totalPages = 10(0-indexed pages0through9).- Elements on final page (
page = 9):137 - 135 = 2books.
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.
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:
@Transactionalwraps 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
@Entityobjects in the Persistence Context. Modifying an entity via a setter (e.g.,student.setGpa(3.85)) automatically triggers anUPDATESQL statement before commit without needing an explicitsave()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().
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.