Top Banner Ad

BCS403 — Unit 5: Spring Framework

Table of Contents (22 sections)

BCS403 · Object Oriented Programming with Java · Unit 5

Spring Framework

Unit Scope & Exam Weightage: This unit covers Spring Core / Dependency Injection, Inversion of Control, AOP, bean scopes (singleton, prototype, request, session, application, WebSocket), autowiring, annotations, life-cycle callbacks, bean configuration styles, Spring Boot build systems, code structure, runners, logger, and RESTful web services with @RestController, @RequestMapping, @RequestBody, @PathVariable, @RequestParam and GET/POST/PUT/DELETE APIs. Every one of the 11 PYQ clusters in this unit is a real exam question — no predicted question is needed here.


Importance-Wise Roadmap (BCS403 Unit 5)

Priority Exact Syllabus Topic PYQ Evidence Marks Pattern Tag
1 Dependency Injection + Spring IoC container 2023-24, 2024-25, 2025-26 7m × 4 Guaranteed
2 Life Cycle Call backs / Spring bean life cycle 2023-24, 2025-26 7m × 2 Sequence answer
3 RESTful Web Services + Spring Boot REST API 2023-24, 2025-26 7m × 2 + 7m CRUD Code + flow
4 Spring Boot vs Spring, code structure, build systems 2024-25 7m × 2 Comparison
5 AOP, GET vs POST 2025-26, 2024-25 2m × 2 Quick marks
6 Bean Scopes, autowiring, annotations, runners, logger, Web applications Not directly asked Predicted Complete coverage

Spring-specific examiner guidance: Always name the container (ApplicationContext), the bean, and the exact annotation or callback in a theory answer. For REST questions draw the request path Client → DispatcherServlet → Controller → Service → Repository → JSON before writing code.


1. Spring Core, IoC and Dependency Injection

Spring: a lightweight Java framework whose core is an Inversion of Control (IoC) container. The container creates objects called beans, wires their dependencies, manages their life cycle and supplies cross-cutting services such as transactions and logging.

1.1 DI with a Real-World Example

PYQ (2025-26, 7 marks): "Explain Dependency Injection with a real-world example. How does Spring's Inversion of Control container manage these dependencies?"

Real-world analogy: a Car needs an Engine. Previously the Car built its own engine with new PetrolEngine() — it was responsible for creation and therefore tightly coupled. With DI, the factory (Spring container) supplies the engine through the constructor; the Car only declares what it needs.

import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

interface Engine { void start(); }

@Component
class PetrolEngine implements Engine {
    public void start() { System.out.println("Petrol engine starts"); }
}

@Component
class Car {
    private final Engine engine;
    @Autowired                       // constructor injection (recommended)
    Car(Engine engine) { this.engine = engine; }
    void drive() { engine.start(); System.out.println("Car moves"); }
}

How the IoC container manages it:

  1. @Component classes are discovered by component scanning (@SpringBootApplication includes it).
  2. Each discovered class becomes a bean definition with a name and scope.
  3. ApplicationContext instantiates beans, resolving constructor parameters by type (and @Qualifier by name when several candidates exist).
  4. It injects the matched dependency, applies BeanPostProcessors and lifecycle callbacks, and stores the ready bean in its singleton cache.
  5. Client code asks ctx.getBean(Car.class) and receives a fully wired object; it never calls new Car(new PetrolEngine()).
  6. At shutdown the container invokes destruction callbacks.

Benefits: loose coupling, easy unit testing with mock dependencies, centralised configuration, and replaceable implementations without editing the consumer class.

1.2 DI vs IoC

PYQ (2023-24, 7 marks): "Explain the difference between Dependency Injection (DI) and Inversion of Control (IoC) in Spring."

Basis Inversion of Control (IoC) Dependency Injection (DI)
Meaning General principle: control of object creation/lifetime moves from the program to a framework A specific pattern for supplying dependencies to an object
Scope Umbrella term One implementation of IoC
Who calls whom Framework calls application code (Hollywood Principle: "don't call us, we'll call you") Container passes collaborators via constructor/setter/field
Example in Spring ApplicationContext creating and destroying beans @Autowired Engine engine in Car
Without it Application uses new and manages everything Application builds its own dependencies

Relationship: IoC is the goal (framework controls the flow); DI is the mechanism used by Spring to achieve it. Other IoC mechanisms include callbacks and template methods.

1.3 Types of Dependency Injection

PYQ (2024-25, 7 marks): "Explain the concept of Dependency Injection and its types in Spring. Develop a simple API in Spring Boot to perform CRUD operations using a list as storage."

Types: (1) constructor injection — dependencies supplied in the constructor; guarantees immutable, non-null fields and is recommended; (2) setter injection — via a @Autowired setter, allows optional/replaceable dependencies; (3) field injection — @Autowired directly on a field; shortest but hides dependencies and prevents final fields, so avoid in production code.

CRUD REST API using an in-memory list:

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/students")
public class StudentController {
    private final List<Student> store = new CopyOnWriteArrayList<>();
    private final AtomicInteger seq = new AtomicInteger(1);

    @GetMapping                                     // READ all
    public List<Student> all() { return new ArrayList<>(store); }

    @GetMapping("/{id}")                            // READ one
    public ResponseEntity<Student> one(@PathVariable int id) {
        return store.stream().filter(s -> s.id == id).findFirst()
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PostMapping                                    // CREATE
    public Student create(@RequestBody Student s) {
        s.id = seq.getAndIncrement();
        store.add(s);
        return s;
    }

    @PutMapping("/{id}")                            // UPDATE
    public ResponseEntity<Student> update(@PathVariable int id,
                                          @RequestBody Student s) {
        for (Student old : store) {
            if (old.id == id) { old.name = s.name; return ResponseEntity.ok(old); }
        }
        return ResponseEntity.notFound().build();
    }

    @DeleteMapping("/{id}")                         // DELETE
    public ResponseEntity<Void> delete(@PathVariable int id) {
        return store.removeIf(s -> s.id == id)
                ? ResponseEntity.noContent().build()
                : ResponseEntity.notFound().build();
    }

    public static class Student {
        public int id;
        public String name;
        public Student() { }                         // required for JSON binding
        public Student(int id, String name) { this.id = id; this.name = name; }
    }
}
Operation HTTP request Result
Create POST /api/students with JSON {"name":"Aditi"} {"id":1,"name":"Aditi"}
Read all GET /api/students Array of students
Read one GET /api/students/1 One student or 404
Update PUT /api/students/1 with {"name":"Neha"} Updated student or 404
Delete DELETE /api/students/1 204 No Content or 404

CopyOnWriteArrayList keeps concurrent reads safe; a real application would replace the list with a Spring Data repository.


2. Spring Container, Bean Scopes, Autowiring and Annotations

2.1 Spring Container

PYQ (2023-24, 7 marks): "Describe following: 1. Spring container 2. Spring bean life cycle"

The Spring container is the runtime environment that manages beans. BeanFactory provides basic IoC with lazy instantiation; ApplicationContext extends it and adds component scanning, event publishing, internationalisation, AOP integration and eager singleton creation. Common implementations: ClassPathXmlApplicationContext (XML configuration), AnnotationConfigApplicationContext (Java @Configuration), and the embedded context created by Spring Boot.

Bean scopes (syllabus list):

Scope Instances created Use case
singleton (default) One per container Stateless services, controllers, repositories
prototype New object per getBean()/injection Stateful objects, builders
request One per HTTP request Request-scoped form data (web-aware context)
session One per HTTP session User cart/preferences
application One per ServletContext Application-wide web state
websocket One per WebSocket session STOMP/WebSocket handlers
@Component
@Scope("prototype")
class ReportBuilder { }

Stateful beans must not be singleton; otherwise one user's data leaks into another's request.

2.2 Autowiring and Annotations

Autowiring is the container's automatic satisfaction of a bean's dependencies. Modes: byType (unique bean of the required type), byName (bean id matches the property name), constructor (constructor arguments), and no (explicit refs). Annotation-driven wiring uses @Autowired on constructors/fields/setters.

Annotation Meaning
@Component, @Service, @Repository, @Controller, @RestController Stereotypes that register beans; @RestController = @Controller + @ResponseBody
@Configuration + @Bean Java configuration class and explicit factory method
@Autowired Inject matching bean by type
@Qualifier("name") Choose among several beans of the same type
@Primary Default candidate when several exist
@Value("${prop}") Inject property value
@Scope Select bean scope
@SpringBootApplication @Configuration + @EnableAutoConfiguration + @ComponentScan
interface Notifier { void send(String msg); }
@Component("email") class EmailNotifier implements Notifier { public void send(String m) {} }
@Component("sms")   class SmsNotifier implements Notifier { public void send(String m) {} }
@Service
class AlertService {
    private final Notifier n;
    AlertService(@Qualifier("email") Notifier n) { this.n = n; }  // resolves ambiguity
}

2.3 Bean Life Cycle and Callbacks

PYQ (2025-26, 7 marks): "Explain the Spring Bean Lifecycle. Describe the steps from when a bean is instantiated until it is destroyed by the container."

Bean definition loaded -> instantiate -> populate properties (DI)
   -> set BeanName/BeanFactory/Environment aware callbacks
   -> BeanPostProcessor.beforeInitialization
   -> @PostConstruct -> InitializingBean.afterPropertiesSet() -> custom init-method
   -> BeanPostProcessor.afterInitialization (AOP proxies created here)
   -> BEAN READY IN CONTAINER
   -> container shutdown -> @PreDestroy -> DisposableBean.destroy() -> custom destroy-method
Step Callback Typical use
1 Constructor Allocate object; constructor injection
2 Setter/field injection Wire dependencies
3 *Aware methods Obtain bean name, context, resource loader
4 BeanPostProcessor.postProcessBeforeInitialization Annotation processing
5 @PostConstruct / afterPropertiesSet() / init-method Open files, warm caches, validate configuration
6 postProcessAfterInitialization Wrap bean in proxy (transactions, AOP)
7 @PreDestroy / destroy() / destroy-method Close connections, flush buffers
@Component
class CacheWarmers {
    @jakarta.annotation.PostConstruct
    void init() { System.out.println("bean ready"); }
    @jakarta.annotation.PreDestroy
    void cleanup() { System.out.println("bean destroyed"); }
}

If several initialization mechanisms are present they run in the order shown; @PostConstruct runs before afterPropertiesSet. Destruction order is reversed relative to creation for dependencies.


3. Spring Boot, Configuration, Build Systems and Runners

3.1 Spring Boot vs Traditional Spring

PYQ (2024-25, 7 marks): "What is Spring Boot? How is it different from the traditional Spring framework?"

Spring Boot is an opinionated layer over Spring that auto-configures the application from the dependencies on the classpath and packages it as an executable JAR with an embedded server.

Traditional Spring Spring Boot
Extensive XML or Java configuration Auto-configuration via @EnableAutoConfiguration
External Tomcat/WAR deployment Embedded Tomcat; runnable JAR via java -jar
Manual dependency version management Starter POMs + parent BOM align versions
Many explicit beans for common infrastructure Conditional beans created only when needed
Separate properties/plumbing code application.properties/.yml + @ConfigurationProperties
Slower prototype setup spring-boot-starter-web gives a REST app in minutes

3.2 Code Structure and Build Systems

PYQ (2024-25, 7 marks): "Describe the structure of a basic Spring Boot application. What are the advantages of using Spring Boot over traditional web frameworks?"

StudentApp/
  pom.xml  (or build.gradle)
  src/main/java/in/ac/aktu/studentapp/
      StudentAppApplication.java     @SpringBootApplication + main()
      controller/StudentController.java
      service/StudentService.java
      repository/StudentRepository.java
      model/Student.java
  src/main/resources/
      application.properties
      static/  templates/
  src/test/java/...
@SpringBootApplication
public class StudentAppApplication {
    public static void main(String[] args) {
        SpringApplication.run(StudentAppApplication.class, args);
    }
}

Advantages: zero XML, embedded server, production-ready Actuator endpoints, externalised configuration with profiles, easy testing with @SpringBootTest, starters, and independent deployment.

Build systems: Maven uses spring-boot-starter-parent, spring-boot-starter-web, spring-boot-maven-plugin; Gradle uses org.springframework.boot plus io.spring.dependency-management plugins. A starter is a curated dependency descriptor — spring-boot-starter-web brings Spring MVC, Jackson and Tomcat transitively.

3.3 Spring Boot Runners

A runner executes code once after the context is ready — ideal for seeding master data or printing startup diagnostics.

@Component
class StartupTasks implements ApplicationRunner, CommandLineRunner {
    public void run(ApplicationArguments args) { System.out.println("ApplicationRunner: " + args.getSourceArgs().length); }
    public void run(String... args) { System.out.println("CommandLineRunner: " + args.length); }
}

ApplicationRunner receives parsed ApplicationArguments; CommandLineRunner receives the raw String[]. Both run before the web server begins serving requests; use @Order to sequence them.

3.4 Logger

Spring Boot uses SLF4J with Logback by default. Parameterised placeholders avoid string-building cost when a level is disabled.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FeeService {
    private static final Logger log = LoggerFactory.getLogger(FeeService.class);
    void charge(int roll, double amount) {
        log.debug("Charging roll {}", roll);
        log.info("Amount credited: {}", amount);
        log.warn("Gateway slow");
        log.error("Payment failed for roll {}", roll);
    }
}

Levels: TRACE < DEBUG < INFO < WARN < ERROR. Configure logging.level.in.ac.aktu=DEBUG and logging.file.name=app.log in application.properties.


4. AOP and RESTful Web Services

4.1 Aspect-Oriented Programming

PYQ (2025-26, 2 marks): "What is Aspect-Oriented Programming (AOP) and how it helps with logging without touching the main business logic?"

AOP separates cross-cutting concerns — logging, security, transaction management, auditing — from business methods. An aspect is the module containing advice; advice is the code run at a join point (method call/exception); a pointcut is the expression selecting join points; weaving inserts the advice at runtime in Spring.

@Aspect
@Component
public class LoggingAspect {
    private static final Logger log = LoggerFactory.getLogger(LoggingAspect.class);

    @Around("execution(* in.ac.aktu.app.service.*.*(..))")
    public Object timeMethod(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        try {
            return pjp.proceed();                 // original business method
        } finally {
            log.info("{} took {} ms", pjp.getSignature().getName(),
                     System.currentTimeMillis() - start);
        }
    }
}

The service code contains no logging statements, so a timing change affects one class rather than every service. Advice types: @Before, @After, @AfterReturning, @AfterThrowing, @Around (the most powerful).

4.2 REST Architecture and Request Flow

PYQ (2025-26, 7 marks): "Explain the architecture of a RESTful Web Service. How does Spring Boot handle a client request and return a JSON response?"

REST is a stateless architectural style in which resources are identified by URLs and manipulated with standard HTTP verbs. Spring Boot implements it through Spring MVC.

Client (browser / Postman / mobile app)
        |  HTTP request + JSON body
        v
Embedded Tomcat -> DispatcherServlet (Front Controller)
        v
HandlerMapping finds controller method
        v
HandlerAdapter -> @RestController -> @Service -> @Repository
        v
Returned object -> Jackson HttpMessageConverter -> JSON response

Step-by-step: (1) @RestController marks the class and makes returned objects become response bodies; (2) @RequestMapping/@GetMapping map a URL and verb to a method; (3) @RequestBody uses Jackson to deserialise JSON into a Java object; (4) @PathVariable extracts /{id} and @RequestParam extracts ?key=value; (5) the service/repository performs work; (6) the returned Java object is serialised back to JSON with content type application/json; (7) an appropriate status code (200, 201, 204, 404) is sent. Statelessness means every request carries all information needed — typically a token, not a server-side session.

@RestController
@RequestMapping("/api/books")
public class BookController {
    @GetMapping("/{id}")
    public Book get(@PathVariable int id,
                    @RequestParam(defaultValue = "false") boolean brief) {
        return new Book(id, brief ? "Title only" : "Full details");
    }
}

A call to GET /api/books/7?brief=true yields {"id":7,"title":"Title only"}.

PYQ (2023-24, 7 marks): "Describe following: 3. Spring boot framework and its benefits 4. RESTFUL API with Spring boot" Combine §3.1/§3.2 for part 3 and §4.2 plus the CRUD code in §1.3 for part 4.

4.3 Mapping Annotations and HTTP Verbs

Annotation Verb Purpose Example
@GetMapping GET Read resource(s); safe and idempotent /api/students
@PostMapping POST Create resource; body in @RequestBody /api/students
@PutMapping PUT Replace/update whole resource; idempotent /api/students/1
@PatchMapping PATCH Partial update /api/students/1
@DeleteMapping DELETE Remove resource /api/students/1
@RequestMapping any Class-level base path or custom method /api

PYQ (2024-25, 2 marks): "What is a GET vs POST request?"

GET POST
Retrieves data Submits/creates data
Parameters in URL query string Data in request body
Safe and idempotent; cacheable Neither safe nor idempotent by default
Limited URL length Practically unlimited body size
Should have no side effects Usually changes server state
@GetMapping @PostMapping + @RequestBody

4.4 Building Web Applications

Beyond JSON APIs, Spring Boot serves static resources from src/main/resources/static and server-side templates from templates/ (Thymeleaf, Freemarker) via Spring MVC. Add spring-boot-starter-thymeleaf, return a view name from a @Controller method, and place list.html in templates/. This supports conventional web applications while REST controllers serve machine clients from the same context.


5. Exam-Ready Question Index and Practice

Question (source) Solution location
DI with real-world example + IoC container (2025-26, 7m) §1.1
DI types + CRUD API using list (2024-25, 7m) §1.3
DI vs IoC (2023-24, 7m) §1.2
Spring container + bean life cycle (2023-24, 7m) §2.1 + §2.3
Spring bean lifecycle callbacks (2025-26, 7m) §2.3
REST architecture + JSON response (2025-26, 7m) §4.2
Spring Boot and REST API (2023-24, 7m) §3.1 + §4.2
Spring Boot vs traditional Spring (2024-25, 7m) §3.1
Boot application structure and advantages (2024-25, 7m) §3.2
AOP logging (2025-26, 2m) §4.1
GET vs POST (2024-25, 2m) §4.3

Practice questions (label: practice, not real PYQs)

  1. Practice: Declare a prototype bean and prove with two getBean() calls that distinct instances are returned.
  2. Practice: Add @Qualifier("sms") to AlertService and explain how the injected implementation changes.
  3. Practice: Add @Valid and @RequestBody to the create API and describe what happens on an invalid payload.
  4. Practice: Write an @AfterReturning advice that logs the value returned by a service method.
  5. Practice: Configure two profiles (dev, prod) with different application-*.properties files and activate one.

6. Last-Night Survival Checklist (Unit 5 only)

  1. Container vocabulary: bean = container-managed object; ApplicationContext = IoC container; DI = constructor/setter/field injection; IoC = framework controls creation.
  2. Lifecycle order: construct → inject → aware callbacks → before-init → @PostConstruct → afterPropertiesSet → init-method → after-init/proxy → ready → @PreDestroy → destroy.
  3. Six scopes: singleton, prototype, request, session, application, websocket — know which are web-aware.
  4. REST mapping: GET/POST/PUT/DELETE with @GetMapping, @PostMapping, @PutMapping, @DeleteMapping; @PathVariable for /{id}, @RequestParam for ?q=, @RequestBody for JSON.
  5. Boot essentials: @SpringBootApplication, starter dependencies, embedded server, application.properties, ApplicationRunner/CommandLineRunner, SLF4J logger, @Aspect for AOP.

Final Spring reminder: A 7-mark answer should contain one concrete annotation example and one numbered flow. For bean lifecycle number the callbacks; for REST draw the DispatcherServlet path. These two habits make a Spring answer look implementation-aware rather than memorised.