back
Spring Boot - Introduction
Spring Boot has quickly become the go-to framework for building production-ready applications with minimal setup. It abstracts away a lot of boilerplate, offers built-in starters, and makes deployment effortless. But WHY SPRINGBOOT?
Why Spring Boot?
There are 3 major problems that spring boot solves:
Tight Coupling
Spring Boot tackles tight coupling head-on through its use of the Inversion of Control (IoC) container and Dependency Injection (DI). Instead of you manually creating objects and their dependencies (
new MyClass()
), the Spring container manages this for you. You simply declare what a class needs (@Autowired
), and Spring provides the required instance. This decouples components because a class no longer knows how to create its dependencies; it only knows how to use them.Scattered Object Creation
This problem is solved by Spring Boot's IoC container. The container acts as a central registry for all the objects (or "beans") in your application. By using annotations like
@Component
,@Service
, or@Repository
, you tell Spring which classes it needs to manage. Spring then takes care of their creation, configuration, and lifecycle. This eliminates the need for you to manually manage object creation across your application, keeping it organized and consistent.Hard to Test
Spring Boot makes testing significantly easier by providing a comprehensive testing framework. The
@SpringBootTest
annotation allows you to load an application context specifically for testing, and you can easily mock dependencies using annotations like@MockBean
or@SpyBean
. This makes it simple to test individual components in isolation (unit tests) or verify how multiple components work together (integration tests) without having to start a full, external server or database.Every class creates its own obj. using
new
spreading obj lifecycle and config logic throughout the app.All these probs like Tight Coupling, Scattered Object Creation, Testing and many more can go away with the intro of Dependency Injection and IOC(Inversion of Control) container ( or Spring Container ).
NOTE: Don't worry about this jargon, we'll cover each term later.
What is Spring?
Spring is a framework that helps you create enterprise Java application. It enables you to build Java apps from POJO (Plain Old Java Obj). Provides a comprehensive ecosystem (Spring MVC, Spring Data, Spring Security, etc.) for building scalable applications.
- Spring Framework provides the IoC container (like
ApplicationContext
) which manages the lifecycle of beans and injects dependencies.
Spring Boot builds on top of Spring Framework, it still uses DI/IoC under the hood, but adds auto-configuration and starter dependencies so you don’t have to write as much configuration code manually.
Spring = IoC + DI |
Spring Boot = Spring + Auto Configuration + Starters + Embedded Server |
Dependency Injection & IOC
Java application typically consists of objects that collaborate to form one proper application.
Many objects in the application have dependencies on each other.
Although Java platform provides many application development functionality, it lacks the means to organize all these building blocks.
IOC component addresses this concern by providing a formalized means of composing disparate components into a fully working application.
Modules:
Spring framework consists of 20 modules, grouped into:
Core Container
Data Access/Integration
AOP (Aspect Oriented Prog.)
Instrumentation
Web
Test
1) Core Container:
Consists of Core, Beans, Context & Expression Language.
Core & Beans → fundamental part of framework, including IOC & DI features.
Context → a means to access obj in framework-style manner, builds on solid base provided by Core & Beans.
Expression Lang. → provides expression lang for querying and manipulating an obj graph at runtime.
2) Data Access/Integration:
Consists of JDBC, ORM, OXM, JMS and Transaction modules.
JDBC → provides connectivity to DB.
ORM → provides Object Relational Mapping API (including JPA, Hibernate).
OXM → provides abstract layers that support Obj/XML mapping implementation for Jaxb, XMLBeans.
JMS (Java Messaging Services) → producing/consuming msgs.
Transaction → supports programmatic & declarative transaction management for classes that implement interfaces for all your POJOs.
3) AOP (Aspect-Oriented Programming)
Provides aspect-oriented features such as method interceptors and pointcuts.
Allows separation of cross-cutting concerns like logging, transaction management, and security.
4) Instrumentation
Provides class instrumentation support.
Includes classloader implementations to be used in certain application servers.
5) Web:
Consists of web, web-servlet, web-struts, web-Portlet.
web → provides web-oriented integration like initialization of IOC container in servlet.
web-Servlet → contains MVC for implementing web apps.
Web-Struts → Support for integrating with Struts framework.
Web-Portlet → MVC implementation for Portlet environments.
6) Test:
- Supports testing of Spring components via JUnit/TestNG.
IOC & DI
Objects define their dependencies only through constructor arguments, arguments to a factory method, or properties that are set on an obj instance after it is constructed or returned from a factory method.
The container then injects those dependencies when it creates the bean.
This process is fundamentally inverse of the bean itself controlling the instantiation/creation of its dependencies on its own by using direct constructor or classes.
DI is a specialized form of IOC.
In simple words:
IOC means letting the framework control the creation and management of objects, instead of doing it manually.
Example: Instead of writing:
Service service = new Service();
Spring creates the
service
obj for you.
DI:
A way to provide objects (dependencies) that a class needs, instead of class creating them itself.
Spring injects these dependencies automatically, either through constructor, setter, or fields.
Real Life Analogy:
Imagine yourself at a restaurant:
Without IOC: you go into the kitchen and cook your food.
With IOC & DI: you just sit at the table, and the waiter (Spring) brings your meal (dependencies) to you.
Spring History
Early 2000s – Java EE Apps
Complex, heavyweight
Difficult to test & maintain
2004 – Rod Johnson open-sourced the Spring framework
Added IOC, DI
Rapidly adopted by enterprise developers
2009 – Sold to VMware ($420M)
2004–2017 – Spring framework evolved
Added Java-based configuration (post-XML based)
Added support for Java 8
Embraced microservices, reactive programming
2014 – Spring Boot was released
Auto-configuration
Starter dependencies
Embedded servers (Tomcat, Jetty)
Production-ready features (health checks, metrics)
First, let's cover some Spring basics before we get into Spring Boot.
Spring Framework
1) Inversion of Control (IOC):
It is a design principle where the control of object creation and management is transferred from developer to container (like Spring).
In traditional Java, you would manually create objects. With IOC, Spring creates and wires objects for you.
Example:
Without IOC:
Service service = new Service();
With IOC:
@Component public class Service { // Spring creates and manages this }
Spring automatically instantiates
Service
and injects it wherever needed.
2) Dependency Injection (DI):
It is a form of IOC where the required dependencies of a class (its collaborators) are provided to it rather than the class creating them itself.
3 types of DI:
Constructor Injection
Setter Injection
Field Injection
Example:
@Component
public class OrderService {
private final PaymentService paymentService;
@Autowired
public OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}
}
- Spring injects
PaymentService
automatically intoOrderService
.
3) Spring Beans and Bean Lifecycle
A bean is an object that is instantiated, assembled, and managed by Spring IOC container.
Spring manages the lifecycle of beans:
Instantiation
Dependency Injection
Initialization (
@PostConstruct
)Destruction (
@PreDestroy
)
Example:
@Component
public class MyBean {
@PostConstruct
public void init() {
System.out.println("Bean initialized");
}
@PreDestroy
public void destroy() {
System.out.println("Bean about to be destroyed");
}
}
4) Configuration & @Configuration
Java-based configuration replaces XML in modern Spring apps.
Allows defining beans using
@Bean
method inside a class marked with@Configuration
.
Example:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
- By doing this, Spring will register
myService
as a bean.
5). Component Scanning
Spring framework automatically discovers and registers components (classes) that become beans in the application context.
Spring scans specified packages in your application classpath for classes annotated with special annotations like
@Component
,@Service
,@Repository
,@Controller
.When Spring finds these annotations, it automatically registers these classes as Spring beans inside the application context, eliminating the need for manual bean declaration in XML files or configuration classes.
Customize scan by:
@ComponentScan(basePackages = "com.example")
6). Spring Annotation Overview
@Component
– Generic stereotype for any Spring-managed component.@Service
– Marks a service layer class.@Repository
– Marks as DAO and adds exception translation.@Controller
– Marks a web controller (returns view).@RestController
– Combines@Controller
+@ResponseBody
(returns JSON).@Autowired
– Injects dependency automatically.@Qualifier
– Used with@Autowired
when multiple beans of the same type exist.
7). Spring MVC
- Spring MVC is a web framework, part of Spring, that helps building RESTful APIs.
Key Annotations:
@Controller
– For handling web pages (HTML).@RestController
– For REST APIs (returns JSON).@RequestMapping
– Maps HTTP requests to methods.@GetMapping
,@PostMapping
– Shorthand for request mappings.
Example:
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello";
}
}
8). Spring ApplicationContext
- It is the core interface in Spring that holds all the beans and handles the lifecycle, DI, and events.
Key Points:
It’s the Spring container.
You can get any bean from it manually using:
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); MyBean myBean = context.getBean(MyBean.class);
On Spring Boot, this is done automatically.
9). Aspect-Oriented Programming (AOP)
AOP allows you to separate cross-cutting concerns like logging, security, transactions, etc.
Instead of writing logging code in every method, you can define it in one place and apply it across methods.
Example:
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*(..))")
public void logBefore(JoinPoint jp) {
System.out.println("Method called: " + jp.getSignature());
}
}
10). Spring Data JPA
- It makes working with DB entities easy using JPA (Java Persistence API).
Key Annotations:
@Entity
– Marks class as table.@Id
– Primary key.@GeneratedValue
– Autogeneration of ID.
Example:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
- In Spring Boot, you just define the interface, no implementation needed.
Spring Boot:
Spring Boot is a Java framework that makes it easy to create stand-alone, production-ready Spring applications with very little setup.
An extended version of Spring framework (annotations).
It removes the need for complex configuration by providing:
Auto-configuration (Spring sets things up for you)
Embedded servers (like Tomcat, so no need to deploy WAR files)
Starter dependencies (pre-built packages for common use cases)
Spring Framework + AutoConfig + Conventions + Tools = Spring Boot |
Internal Working of Spring Boot
Component Scanning starts from the entry point (main() method) where it’s invoked
SpringApplication.run
()
.Beans are Java objects managed by the IoC (Inversion of Control) Container.
Tight Coupling: when the main application code is directly dependent on another component’s code.
To overcome (loose coupling), we use two methods:
Constructor Injection – By creating constructors and passing dependencies as arguments, so the main app is dependent on that component annotated with
@Component
. This is called Constructor DI.Field Injection – Using annotation
@Autowired
.
Internal working of Spring boot - visual representation:
When you run the Spring application, the IOC container first wants to create Application Context which is nothing but a bunch of Beans, so IOC container, based on env variables or properties takes the POJO classes and start component scanning and where it finds the
@Component
annotated, it creates the bean of that component and stores it in Application Context.So now our application, whenever and wherever requires a bean, this application context provides the necessary bean and we don’t need to create any obj using
new
keyword, after beans are created, the request will go to dispatcher servlet and the dispatcher servlet will distribute all the request to appropriate controllers.IOC container checks or scan only those components or classes that are annotated with
@Component
. With@Component
annotation, Spring creates bean automatically but you can also create bean manually. For that you have use@Bean
inside@Configuration
.Component Scanning: It starts from
@SpringBootApplication
which is present in the root file. Under this annotation, there is@ComponentScan
annotation which tells it to scan for@Components
from this root level so that we can create beans of the required classes.Inside
@SpringBootApplication
there is another annotation@EnableAutoConfiguration
, which is one of the main thing of Spring Boot.Auto config on top of Spring framework, we get Spring Boot.
With the help of this auto-configuration, different kinds of dependencies get auto configured into your project.
So If you check in dependency folder, you’ll find a
"maven:org.springframework.boot:spring-boot-autoconfig"
and if you open this and then go to spring folder and if you open import file you’ll see all the dependencies / AutoConfig files
What happens when you run a Spring Boot Application
JVM starts the app and
main()
method is executedSpringApplication.run
(MyApp.class, args)
→ Inside thisrun
method, inside this againrun
method is executedSpringBoot detects
@SpringBootApplication
on MyApp.class which includes:@SpringBootConfiguration
→ marks as@Configuration
@ComponentScan
→ scans current package & sub-packages@EnableAutoConfig
→ loads auto-config from Spring factories
Creates a SpringApplication object:
Sets up Application Context
Sets up Environment
Registers Listeners, Initializers
Application Context is created
Environment is prepared (e.g. application.properties, args)
Beans are scanned and registered via
@ComponentScan
and Auto-configured beans are registered (e.g. DataSource, WebServer)ApplicationContext is refreshed
All beans are created
Dependencies are autowired
Lifecycle methods are called
Embedded web server (e.g., Tomcat) is started. Binds it to a port (8080), registers DispatcherServlet as front controller of MCV
CommandLineRunner or ApplicationRunner beans (if any) are executed
Application is now fully started and ready to serve requests. And handles all HTTP requests
Internal Working - Detailed version
1. Application Entry Point (Main Class)
Every Spring Boot application starts with a main()
method annotated with @SpringBootApplication
.
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
This calls:
SpringApplication.run(MyApp.class, args);
This is the starting point of the Spring Boot engine.
2. @SpringBootApplication Explained
This is a combination of 3 annotations:
@Configuration // Marks this class as a configuration source
@EnableAutoConfiguration // Triggers auto-configuration
@ComponentScan // Enables component scanning for current package & subpackages
So it:
Registers beans from the current package downward
Automatically configures many things (DataSource, DispatcherServlet, etc.)
3. SpringApplication.run()
This is the heart of Spring Boot. It performs these steps internally:
a. Creates a SpringApplication object
This prepares the context, listeners, and initializers.
b. Loads ApplicationContext
Instantiates the IoC container (typically
AnnotationConfigApplicationContext
)Scans for components (
@Component
,@Service
, etc.)Instantiates and wires beans using Dependency Injection
c. Applies Auto-Configuration
Thanks to
@EnableAutoConfiguration
, Spring Boot:Reads
spring.factories
to load auto-configuration classesApplies configurations only if needed (conditional on classpath, properties, etc.)
Example:
If Spring finds spring-boot-starter-web
, it auto-configures:
Embedded Tomcat
DispatcherServlet
JSON converters
4. Embedded Server Setup
If it’s a web application:
Spring Boot auto-configures an embedded server (like Tomcat, Jetty, or Undertow)
Binds it to a port (default: 8080)
Registers the DispatcherServlet, the front controller of Spring MVC
5. Component Scanning and Bean Creation
Spring scans the package of the main class for:
@Component
@Service
@Repository
@Controller
or@RestController
Each is created as a Spring Bean and stored in the ApplicationContext.
Dependency Injection is applied wherever @Autowired
is used.
6. Handling HTTP Requests
When a request like GET /hello
hits the server:
The embedded server receives the request
The DispatcherServlet (front controller) handles it
It uses HandlerMapping to find the matching
@Controller
methodThe method is executed, and response is returned (e.g., JSON)
Example:
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hi!";
}
}
7. External Configuration
Spring Boot reads external configuration from:
application.properties
orapplication.yml
Environment variables
Command-line args
Profiles (e.g.,
application-dev.properties
)
These values are injected using @Value
or bound via @ConfigurationProperties
.
8. Actuator, Metrics & Monitoring (Optional)
If you add spring-boot-starter-actuator
:
Spring Boot exposes endpoints like:
/actuator/health
/actuator/metrics
/actuator/beans
Helpful for monitoring in production
Summary Diagram (Text-based)
main() ➜ SpringApplication.run()
|
↓
Creates ApplicationContext
|
Auto-configuration & Component Scan
|
Instantiates Embedded Server (Tomcat)
|
Registers DispatcherServlet
|
Scans and wires Beans (DI)
|
Handles incoming HTTP requests
Bonus: Conditional Auto-Config Example
@Bean
@ConditionalOnMissingBean
public DataSource dataSource() {
// only used if you don't define your own DataSource
}
This is why Spring Boot is smart — it only configures defaults when you don’t.
What is Dispatcher Servlet:
Front controller of Spring MVC framework
Acts as a central controller that receives all incoming HTTP requests and routes them to the right component like controllers, views, etc.
Real-life Analogy:
- Think of it as a receptionist in an office
• You walk in and tell them what you need (your request)
• They decide who in the office (or department) can help you
• After getting the info, they get back to you
- Think of it as a receptionist in an office
Working:
Receives the request
Finds matching controller using Handler Mapping
Calls the controller method
Processes the return value (like view/json)
Sends the final response
Internal Working:
HandlerMapping → Finds which controller should handle request
HandlerAdapter → Calls the method in the controller
ViewResolver → Resolves the view (HTML/JSON)
ModelAndView → Holds both model data & view name
Request Flow Example:
Let’s say you hit /hello
GET request
DispatcherServlet
receives/hello
GET requestIt checks for a controller method mapped to
/hello
Let’s say it finds this:
@RestController
public class HelloController {
@GetMapping("/hello")
public String helloWorld() {
return "hello world";
}
}
It invokes
helloWorld()
methodSends
"hello world"
as a response to browser
Next in the series, we’ll explore how to create a REST API in Spring Boot, step by step. Till then Happy Learning.