We conclude the track with Spring. In this module, we will explore Inversion of Control, Constructor Dependency Injection, and REST APIs using Spring Boot 3.
12.1. Spring IoC container & Dependency Injection Autowiring
Definition: IoC transfers class instantiation and configuration control to the framework container. Dependency Injection (DI) injects dependent objects at runtime.
Core Working Principles:
- @Component: Registers a class as a bean managed by the Spring container.
- Constructor Injection: Injects dependencies via the constructor, allowing final fields for thread safety.
@Component
public class ClientApp {
private final MessageService service;
@Autowired // Constructor Injection
public ClientApp(MessageService service) {
this.service = service;
}
}
5-Marks Exam Scoring Points
- IoC container manages bean creation and lifecycles, replacing the `new` keyword.
- Constructor injection is the recommended injection pattern; allows final fields.
- ApplicationContext is the core Spring IoC container interface.
12.2. Spring Boot 3 REST Web Controllers
Definition: Spring Boot 3 simplifies configuration. REST controllers build web endpoints that return raw serialized JSON data.
Core Working Principles:
- Embedded Server: Includes an embedded Tomcat server, running as a standalone JAR.
- @RestController: Combines @Controller and @ResponseBody to build REST APIs.
@RestController
@RequestMapping("/api/students")
public class StudentController {
@GetMapping("/{id}")
public Student get(@PathVariable String id) {
return new Student(id, "Student");
}
}
5-Marks Exam Scoring Points
- Embedded Tomcat web server is packaged directly inside the application JAR file.
- REST controllers serialize returned objects to JSON format automatically.
- Auto-configuration sets up connections and libraries based on dependencies.