Unit V
Unit V
Spring Boot is a way for Java developers to work with the Spring Framework in an easy way. Now, before you
use Spring Boot you need to understand what the Spring Framework is all about. If you've been a Java developer
for any length of time, it's quite likely that you've used some component or the other, which is part of the Spring
Framework because Spring is a Java framework that provides a convenient way of integrating disparate
components into a working enterprise-grade application. The Spring Framework relies heavily on inversion of
control to bring these components together.
Managing dependencies within your
application is a hard task, especially
in Java, when you have several
libraries that you could depend on
to get your task done. Inversion of
Control, implemented using
dependency injection, makes this
easy in Spring. A common scenario
which you might have encountered
is to use Spring modules such as
Spring MVC to build web applications, but Spring is so much more. Spring refers to an entire family of projects
which support a wide range of applications. Spring supports a wide range of enterprise-grade applications,
whether they are web applications, long running batch processing jobs or any other kind. You can use Spring with
simple cloud-hosted servers, standalone batch workloads and integration workloads. A common factor that you'll
encounter across all enterprise-grade applications is their complexity.
The Spring framework itself can be thought of as an infrastructure platform that brings all of these disparate
components together and gets them working together as a whole in an application or a product that you have
built. The cool thing about working with Spring is that you can write development code using POJOs, or Plain Old
Spring Framework
Java Objects. A POJO is just a Java class that you
define to represent any entity within your
application that is not tied to any specific
framework.
Spring allows you to work with POJOs. Spring has
been developed so that it can work with the Java
Standard Edition. Spring also has support for the
Java Enterprise Edition.
Here is a big picture view of the modules included as a part of the Spring Framework runtime. You have data
access and integration modules that use JDBC, ORM frameworks such as Hibernate. All of these serve to abstract
you away from the transaction mechanics of the underlying database. You have a web related modules as well,
which help you build REST services and web
applications. You have modules that enable Aspect
Oriented Programming (AOP), where you can write
code to extend the functionality of existing
components. You have modules for instrumentation
and messaging as well.
2
Spring Framework
Spring Dependency Injection (DI) Concepts
Dependency Injection (DI) is a design pattern used to reduce coupling between components. Instead of
a class creating its dependencies, Spring Framework injects those dependencies at runtime.
// Constructor Injection
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
// Setter Injection
@Autowired
3
Spring Framework
public void setEngine(Engine engine) {
this.engine = engine;
}
@Autowired
private Car car;
@Override
public void run(String... args) {
car.drive();
}
}
Note
• Use @Component to mark classes for Spring to manage.
• Use @Autowired for automatic injection (can be used on constructors, setters, or fields).
• Constructor Injection is recommended for required dependencies and better immutability.
Alternative to @Component
• @Service – for service classes
• @Repository – for DAO classes
• @Controller – for web controllers
Flowchart
4
Spring Framework
Inversion of Control (IoC)
Inversion of Control (IoC) is a principle in which the control of object creation and lifecycle management
is shifted from the application code to the Spring container. In simple term “YOU don’t create objects.
Spring does it for you and injects them where needed.” IoC is implemented in Spring via Dependency
Injection.
public Car() {
this.engine = new Engine(); // tightly coupled
}
5
Spring Framework
@Autowired
private Car car;
@Override
public void run(String... args) {
car.drive();
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
@After("execution(* com.example.demo.PaymentService.*(..))")
public void logAfter(JoinPoint joinPoint) {
System.out.println("LOG: Method finished: " +
joinPoint.getSignature().getName());
}
}
7
Spring Framework
@Autowired
private PaymentService paymentService;
@Override
public void run(String... args) {
paymentService.makePayment("Dhaneshwar", 2500);
}
}
Output
Types of Advice
Annotation Working
@Before Before method execution
@After After method finishes
@AfterReturning After successful method completion
@AfterThrowing After method throws an exception
@Around Before and after method execution
Benefits of AOP in Spring Boot:
• Improved Modularity: Separates cross-cutting concerns from business logic, leading to cleaner
and more focused code.
• Enhanced Reusability: Aspects can be reused across different parts of the application or even in
other projects.
• Reduced Code Duplication: Avoids scattering the same logic throughout multiple classes.
8
Spring Framework
Spring Beans and their Scopes
A spring bean is an object that is
In short, A Spring Bean is just a Java Object whose lifecycle is managed by Spring.
@Component
public class MyService {
public void serve() {
System.out.println("Service is running...");
}
}
Spring provides five core bean scopes (for Spring Framwork, Spring Boot uses primarily the first two)
Example
@Component @Component
@Scope("singleton") // Optional – default @Scope("prototype")
public class SingletonBean { public class PrototypeBean {
public SingletonBean() { public PrototypeBean() {
System.out.println("Singleton created"); System.out.println("Prototype created");
} }
} }
@Autowired
private ApplicationContext context;
9
Spring Framework
}
@Override
public void run(String... args) {
System.out.println("Requesting SingletonBean twice:");
context.getBean(SingletonBean.class);
context.getBean(SingletonBean.class);
10
Spring Framework
@Component
public class MyBean {
public MyBean() {
System.out.println("Constructor: Bean is being created");
}
@PostConstruct
public void init() {
System.out.println("PostConstruct: Bean is initialized");
}
@PreDestroy
public void destroy() {
System.out.println("PreDestroy: Bean is about to be destroyed");
}
}
Runner Application
@SpringBootApplication
public class LifecycleApp {
public static void main(String[] args) {
ConfigurableApplicationContext context =
SpringApplication.run(LifecycleApp.class, args);
context.close(); // Trigger @PreDestroy
}
}
11
Spring Framework
<bean id="myBean" class="com.example.MyBean"/>
</beans>
3. Java Based configuration (JavaConfig) – introduced in Spring 3, allows defining beans using Java
classes and the @Bean annotations. Advantages – type safe, leverages Java language features,
easier to debug and refactor
4. Spring Boot Auto-Configuration – based on the dependencies in our pom.xml or build.gradle,
reducing the need for explicit configuration. Advantages – Minimal configuration, Great for rapid
development.
<parent>
12
Spring Framework
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Commands
mvn clean install – Build the project
mvn spring-boot:run – Run Spring Boot app
2. Gradle – A flexible and faster build tool using build.gradle or build.gradle.kts
Example : build.gradle
plugins {
id 'org.springframework.boot' version '3.2.0'
id 'io.spring.dependency-management' version '1.1.0'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
13
Spring Framework
Component Roles
14
Spring Framework
Example
DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
HelloController.java
package com.example.demo.controller;
import com.example.demo.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
public String sayHello() {
return helloService.getGreeting();
}
}
HelloService.java
package com.example.demo.service;
import org.springframework.stereotype.Service;
@Service
public class HelloService {
public String getGreeting() {
return "Hello from Spring Boot!";
}
}
15
Spring Framework
Spring Boot Runners
In Spring Boot, runners are special interfaces that allow you to run specific code just after the Spring
application context has been loaded and the application has started.
Types of Runners
1. CommandLineRunner – executes code after application starts up, with access to command line
args
2. ApplicationRunner – Similar to CommandLineRunner, but gives access to parsed
ApplicationArguments
Example : CommandLineRunner
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("CommandLineRunner running...");
for (String arg : args) {
System.out.println("Arg: " + arg);
}
}
}
Use Cases of CommandLineRunner
• Initializing data
• Running background processes
• Logging startup diagnostics
Example: ApplicationRunner
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
System.out.println("ApplicationRunner running...");
System.out.println("Option names: " + args.getOptionNames());
}
}
16
Spring Framework
Spring Boot Logger
Logging is essential in any application to trace execution, debug issues, and monitor performance.
Spring Boot provides built-in support for logging using common logging frameworks like:
• SLF4J (Simple Logging Facade for Java) - Spring Boot uses SLF4J for abstraction and Logback as
the default logging implementation.
• Logback (default)
• Log4j2 (optional)
• Java Util Logging (JUL)
Example
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class MyLoggerExample {
logging.level.root=INFO
logging.level.com.example.demo=DEBUG
17
Spring Framework
Project Structure
model.User class
package com.cs2e.user.model;
public User() {
}
UserService.java
package com.cs2e.user.service;
import com.cs2e.user.model.User;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class UserService {
private final Map<Integer, User> userMap = new HashMap<>();
UserController.java
package com.cs2e.user.controller;
import com.cs2e.user.model.User;
import com.cs2e.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public User getUser(@PathVariable int id) {
return userService.getUserById(id);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.addUser(user);
}
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable int id) {
userService.deleteUser(id);
return "User deleted with id: " + id;
}
}
19
Spring Framework
UserApplication.java
package com.cs2e.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
@RestController - A specialized version of @Controller. Marks the class as a web controller and ensures
all return values are automatically serialized as JSON or XML.
@RequestMapping - Used to map HTTP requests to handler methods or classes. Can be used at the
class level (base path) or method level.
@RequestBody - Used to bind the HTTP request body to a Java object. Commonly used with POST, PUT,
or PATCH methods.
20