0% found this document useful (0 votes)
2 views54 pages

Module 1 - Spring Core

The document provides a comprehensive overview of Spring Core, focusing on Inversion of Control (IoC) and Dependency Injection (DI). It explains the problems with traditional Java object creation, the benefits of IoC and DI, and how Spring implements these concepts through its IoC container. Additionally, it includes examples, real-world analogies, and potential interview questions to aid in understanding and preparation for a review meeting.

Uploaded by

try.meraaz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views54 pages

Module 1 - Spring Core

The document provides a comprehensive overview of Spring Core, focusing on Inversion of Control (IoC) and Dependency Injection (DI). It explains the problems with traditional Java object creation, the benefits of IoC and DI, and how Spring implements these concepts through its IoC container. Additionally, it includes examples, real-world analogies, and potential interview questions to aid in understanding and preparation for a review meeting.

Uploaded by

try.meraaz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Spring Core Review Prep 18/03/26, 1:11 PM

ChatGPT Auto

Hey Gpt I have my review meeting on spring core, for which I have
some topics that is provided by our mentors
You have to act as a experienced Spring professor who can easily
explain topics
I will give you that topics and you explain me in depth like I don't know
anything about spring is it clear

Yes, crystal clear!

I’ll act as an experienced Spring professor and explain everything from absolute basics to deeper
concepts, assuming you don’t know anything about Spring. My explanations will include:

Conceptual understanding (what it is and why it exists)


How it works internally
Simple code examples
Real-world analogies
Possible review/interview questions
Key points to remember for your review meeting

So when you send a topic, I will explain it like:

Problem before Spring (Why this concept exists)


What the concept is
How it works internally
Example code
Real-world analogy
Common mistakes / interview questions

This way you’ll be able to explain confidently in your review meeting, not just memorize.

Go ahead and send the first topic from your mentor.

Module 1 – Spring Core


Goal: Understand the foundation of Spring.
Topics to study:
• IoC (Inversion of Control)

Great, let’s start with the most important concept in Spring. Almost everything in Spring Core is built
on IoC. If you understand this well, the rest of Spring becomes much easier.

1. IoC (Inversion of Control) – Spring Core


1.1 The Problem Before IoC
Before frameworks like Spring Framework, Java applications were written like this:

Java

[Link] Page 1 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

class Car {
Engine engine = new Engine();

void drive() {
[Link]();
}
}

What is happening here?


Car creates its own Engine object

Car is tightly coupled to Engine


If we want to change the engine type → we must modify Car

Example:

Java

Engine engine = new DieselEngine();

Later if you want:

Java

Engine engine = new ElectricEngine();

You must change the code of Car class.

Problems
1. Tight Coupling
2. Hard to test
3. Hard to maintain
4. Hard to replace dependencies
5. Object creation logic scattered everywhere

Large enterprise applications became very messy.

1.2 What is IoC (Inversion of Control)?


Inversion of Control means:

Instead of objects creating their dependencies themselves, the framework creates and provides
them.

So the control of object creation is inverted (reversed).

Normally:

Application → creates objects

With IoC:

Framework (Spring) → creates objects

Simple Definition

IoC is a design principle where the control of object creation and dependency management is given to
a container/framework.

In Spring, that container is called:

[Link] Page 2 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Spring IoC Container

1.3 Real-World Analogy


Imagine you join a company office.

Without IoC:

You arrange everything yourself:

chair
laptop
desk
internet
access card

With IoC:

The company provides everything when you arrive.

You only use the resources, you don't create them.

Spring does the same for your objects.

1.4 How IoC Works in Spring


In Spring Framework, the IoC Container:

Creates objects
Manages object lifecycle
Injects dependencies
Configures beans

These objects are called:

Beans

A Bean is simply:

An object managed by the Spring IoC Container.

Flow of IoC in Spring

Developer → writes configuration



Spring IoC Container

Creates Beans

Injects Dependencies

Application uses the Beans

1.5 Example Without IoC

Java

[Link] Page 3 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

class Engine {
void start() {
[Link]("Engine Started");
}
}

class Car {
Engine engine = new Engine();

void drive() {
[Link]();
[Link]("Car Driving");
}
}

Problem

Car is responsible for creating Engine.

1.6 Example With IoC


Now Spring will create the objects.

Engine

Java

@Component
class Engine {

void start() {
[Link]("Engine Started");
}
}

Car

Java

@Component
class Car {

@Autowired
Engine engine;

void drive() {
[Link]();
[Link]("Car Driving");
}
}

What happens?

Spring IoC container:

Creates Engine Bean


Creates Car Bean
Injects Engine into Car

So Car doesn't create Engine anymore.

1.7 Key Components of IoC


Bean

[Link] Page 4 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

A bean is an object managed by Spring.

Example:

Java

@Component
class Engine {}

IoC Container

The container that manages beans.

Two main types:

Container Description

BeanFactory Basic container

ApplicationContext Advanced container (commonly used)

Configuration Metadata
Spring needs instructions to create beans.

This can be done using:

XML configuration
Java configuration
Annotations

Example:

@Component
@Service
@Repository
@Configuration

1.8 Internal Working of IoC


Internally Spring does this:

Start Application

Load Configuration

Create IoC Container

Scan Classes

Create Beans

Resolve Dependencies

Inject Dependencies

Application Ready

[Link] Page 5 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

1.9 Benefits of IoC


Loose Coupling

Objects don't depend on concrete implementations.

Easy Testing

You can inject mock objects.

Better Maintainability

Changing implementation doesn't break code.

Modular Development
Different teams can build different modules.

Reusability
Components can be reused easily.

1.10 IoC vs Dependency Injection


Many people confuse these.

Concept Meaning

IoC Design principle

Dependency Injection (DI) Implementation of IoC

Spring implements IoC using DI.

1.11 Review Meeting Questions (Very Important)


Your mentor may ask:

Q1: What is IoC?


Answer:

IoC is a design principle where the control of object creation and dependency management is transferred
from the application code to the Spring IoC container.

Q2: What problem does IoC solve?


Tight coupling
Difficult testing
Hard maintenance

Q3: What is IoC container?

It is a core component of Spring responsible for:


creating beans
managing lifecycle
injecting dependencies

[Link] Page 6 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Q4: What are the types of IoC containers?

BeanFactory
ApplicationContext

1.12 One-Line Summary


IoC means Spring creates and manages objects instead of the application code doing it manually.

If you want, next I can also explain:


Dependency Injection (very important for review)
Spring Bean
Bean Lifecycle
ApplicationContext vs BeanFactory
Spring Container Internals

These are usually asked together with IoC in reviews.

Just send the next topic from Module 1 and we’ll continue like a Spring masterclass.

Dependency Injection (DI)

Now we move to the most practical concept in Spring Core. Almost every Spring application uses this
concept everywhere.

This concept is Dependency Injection (DI).

Dependency Injection (DI) – Spring Core


Dependency Injection is how Spring Framework actually implements the principle of IoC.

Remember from previous topic:

IoC = design principle


DI = technique used to achieve IoC

[Link] Page 7 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

1. First Understand: What is a Dependency?


A dependency is simply an object that another object needs to work.

Example:

Java

class Engine {
void start(){
[Link]("Engine Started");
}
}

Now a Car needs an Engine.

Java

class Car {

Engine engine = new Engine(); // dependency

void drive(){
[Link]();
[Link]("Car Driving");
}
}

Here:

Car → depends on → Engine

So Engine is a dependency of Car.

2. The Problem Without Dependency Injection


In traditional Java:

Java

class Car {
Engine engine = new Engine();
}

Issues
Tight Coupling

Car is tightly connected to Engine.

If tomorrow we change:

Engine → ElectricEngine

We must change the Car class.

Difficult Testing

During testing we might want:

MockEngine

[Link] Page 8 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

But Car always creates Engine.

Hard to Maintain

Every class manages its own dependencies.

Large applications become messy.

3. What is Dependency Injection?


Simple Definition

Dependency Injection means providing dependencies to an object instead of the object creating
them itself.

Instead of this:

Car creates Engine

We do this:

Spring creates Engine


Spring gives Engine to Car

This process is called injection.

4. Real Life Analogy


Think about ordering a burger at a restaurant.

Without DI:

You must:

grow vegetables
bake bread
cook patty
assemble burger

With DI:

Restaurant provides the burger ready-made.

You just use it.

Spring acts like the restaurant for objects.

5. How Dependency Injection Works in Spring


Inside Spring Framework, the IoC container:

Creates objects (beans)


Finds dependencies
Injects them automatically

[Link] Page 9 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Flow

Application Starts

Spring Container Starts

Beans Created

Dependencies Identified

Dependencies Injected

Application Runs

6. Types of Dependency Injection in Spring


Spring mainly supports 3 types of DI.

1. Constructor Injection (Most Recommended)


Dependencies are provided through the constructor.

Example

Java

@Component
class Engine {

void start(){
[Link]("Engine Started");
}
}

Java

@Component
class Car {

private Engine engine;

public Car(Engine engine){


[Link] = engine;
}

void drive(){
[Link]();
[Link]("Car Driving");
}
}

What Spring Does


Creates Engine bean
Creates Car bean
Passes Engine into constructor

Car(Engine engine)

Why Constructor Injection is Best

[Link] Page 10 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Dependencies become mandatory


Object becomes immutable
Easier unit testing
Recommended by Spring team

2. Setter Injection
Dependency is injected through setter method.

Example

Java

@Component
class Car {

private Engine engine;

@Autowired
public void setEngine(Engine engine){
[Link] = engine;
}
}

How it works

Spring creates Car


Spring calls setEngine()

When Setter Injection is Used

When dependency is optional.

Example:

Car may or may not have MusicSystem

3. Field Injection (Common but Not Recommended)


Dependency injected directly into the field.

Java

@Component
class Car {

@Autowired
Engine engine;
}

Spring injects the dependency automatically.

Why Field Injection is Not Recommended


Hard to test
Breaks encapsulation
Hidden dependencies

[Link] Page 11 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Most modern Spring projects prefer constructor injection.

7. What is @Autowired ?
@Autowired tells Spring:

"Inject the required dependency here."

Example:

Java

@Autowired
Engine engine;

Spring searches for a matching bean type and injects it.

8. What Happens Internally in Spring


Inside the Spring IoC container:

Container scans classes


Finds annotations like

@Component
@Service
@Repository

Creates beans
Looks for dependencies
Injects them

Example internally:

Create Engine Bean


Create Car Bean
Inject Engine → Car

9. Example Flow in a Real Application


Imagine a Spring Boot application.

Controller

Service

Repository

Database

Each layer depends on the next.

Example:

Java

[Link] Page 12 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

@RestController
class UserController {

private UserService service;

public UserController(UserService service){


[Link] = service;
}
}

Spring injects UserService automatically.

10. Benefits of Dependency Injection


1. Loose Coupling

Classes depend on interfaces, not implementations.

2. Easy Testing

You can inject mock objects.

Example:

MockEngine

3. Better Maintainability

Changing implementation doesn't break code.

4. Reusability

Components become reusable.

5. Cleaner Code
Business logic is separated from object creation.

11. Common Interview / Review Questions


Q1: What is Dependency Injection?

Dependency Injection is a design pattern where dependencies of a class are provided by an external
container instead of being created inside the class.

Q2: What are the types of Dependency Injection in Spring?

Constructor Injection
Setter Injection
Field Injection

Q3: Which injection type is recommended?

[Link] Page 13 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Constructor Injection.

Q4: What is @Autowired ?


It tells Spring to automatically inject a dependency from the IoC container.

12. One-Line Summary


Dependency Injection means Spring provides required objects to a class instead of the class
creating them itself.

In your review meeting, DI usually leads to these next topics:

Spring Beans
Bean Lifecycle
Bean Scopes
ApplicationContext vs BeanFactory
Annotations ( @Component , @Service , @Repository )

These are 100% part of Module 1 in most Spring trainings.

Send the next topic from your mentor list, and I’ll explain it like a Spring architect preparing you for
review.

Spring Container

Now we reach the heart of Spring Core. Everything we studied before (IoC and DI) is actually handled by
the Spring Container.

If you understand this concept clearly, you’ll understand how Spring actually works internally.

Spring Container – Spring Core


The Spring Container is the core engine of the Spring Framework.

It is responsible for:

Creating objects (Beans)


Injecting dependencies
Managing bean lifecycle
Configuring application components

[Link] Page 14 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

1. Simple Definition
The Spring Container is responsible for creating, configuring, and managing beans in a Spring
application.

Think of it as the factory and manager of all objects in your application.

2. Why Spring Container Exists


Without Spring Container, developers would have to:
Manually create objects
Manage dependencies
Handle object lifecycle
Configure everything manually

Example without Spring:

Java

Engine engine = new Engine();


Car car = new Car(engine);

In large enterprise systems with hundreds of classes, this becomes impossible to manage.

So Spring introduced the container to automate this process.

3. What the Spring Container Actually Does


When a Spring application starts:

Reads configuration metadata


Creates the container
Creates beans (objects)
Injects dependencies
Manages bean lifecycle

Internal Flow

Plain text

Application Starts

Spring Container Starts

Configuration is Loaded

Beans are Created

Dependencies Injected

Application Ready

4. What is a Bean?
Inside the Spring container, objects are called Beans.

Definition:

[Link] Page 15 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

A bean is an object that is created, managed, and configured by the Spring Container.

Example:

Java

@Component
class Engine {
}

Here Engine becomes a Spring Bean.

5. Real World Analogy


Imagine a company HR department.

Employees = Beans
HR Department = Spring Container

HR does:

Hiring employees
Assigning departments
Managing employees
Providing resources

Similarly, the Spring Container manages application objects.

6. Types of Spring Containers


Spring provides two main container types.

1. BeanFactory (Basic Container)


BeanFactory is the simplest container in Spring.

Characteristics
Lightweight
Lazy initialization
Basic dependency injection

Lazy Initialization
Beans are created only when needed.

Example:

Plain text

Request Bean → Container Creates Bean

Example

Java

BeanFactory factory = new XmlBeanFactory(new ClassPathResource("[Link]"));

[Link] Page 16 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

However, this is rarely used in modern applications.

2. ApplicationContext (Advanced Container)


The most commonly used container is ApplicationContext.

It extends BeanFactory and provides many additional features.

Features of ApplicationContext

Dependency Injection
Event propagation
Internationalization (i18n)
AOP integration
Bean lifecycle management
Automatic bean post processing

Example

Java

ApplicationContext context =
new ClassPathXmlApplicationContext("[Link]");

Then get bean:

Java

Car car = [Link]([Link]);

Spring automatically injects dependencies.

7. Configuration Metadata
Spring Container needs instructions to create beans.

These instructions are called configuration metadata.

There are 3 ways to configure beans.

1. XML Configuration (Old Way)


Example:

XML

<bean id="engine" class="[Link]"/>

<bean id="car" class="[Link]">


<property name="engine" ref="engine"/>
</bean>

Here Spring container reads [Link].

2. Annotation-Based Configuration (Most Common)

[Link] Page 17 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Example:

Java

@Component
class Engine {}

Java

@Component
class Car {

@Autowired
Engine engine;
}

Spring scans the package and creates beans automatically.

3. Java-Based Configuration
Using **Java Configuration in Spring.

Example:

Java

@Configuration
class AppConfig {

@Bean
Engine engine(){
return new Engine();
}
}

8. How the Container Finds Beans


Spring scans packages for annotations like:

Plain text

@Component
@Service
@Repository
@Controller

These annotations mark classes as Spring Beans.

9. Spring Container Lifecycle


When the container starts:

Step 1

Configuration metadata loaded

Step 2

Bean definitions created

[Link] Page 18 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Step 3

Beans instantiated

Step 4

Dependencies injected

Step 5
Beans ready for use

Lifecycle Diagram

Plain text

Load Configuration

Create Container

Instantiate Beans

Inject Dependencies

Initialize Beans

Application Ready

10. Example of Spring Container in Action


Engine

Java

@Component
class Engine {
}

Car

Java

@Component
class Car {

@Autowired
Engine engine;

Main Application

Java

[Link] Page 19 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

ApplicationContext context =
new AnnotationConfigApplicationContext([Link]);

Car car = [Link]([Link]);

What Spring does internally:

Plain text

Create Engine Bean


Create Car Bean
Inject Engine into Car
Return Car Bean

11. Key Responsibilities of Spring Container


The container performs several important tasks:

Object Creation

Creates all beans.

Dependency Injection

Injects required dependencies.

Bean Lifecycle Management


Handles initialization and destruction.

Configuration Management
Reads configuration files.

Bean Scope Management

Controls bean lifetime.

12. Very Important Review Questions


These are very commonly asked in reviews/interviews.

Q1: What is Spring Container?

The Spring Container is the core component of the Spring Framework responsible for creating,
configuring, and managing beans and their dependencies.

Q2: What are the types of Spring Containers?

BeanFactory
ApplicationContext

[Link] Page 20 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Q3: Which container is commonly used?

ApplicationContext

Because it provides additional enterprise features.

Q4: What does the Spring Container manage?


Beans
Dependencies
Lifecycle
Configuration

13. One-Line Summary


The Spring Container is the core component of Spring that creates, configures, and manages
application beans and their dependencies.

In Spring Core Module 1, the next topics usually are:

Spring Beans
Bean Scopes
Bean Lifecycle
Autowired Annotation
Component Annotations

If you want, I can also explain “Spring Bean” next, which is directly connected to the container and is
almost always asked in reviews.

Bean definition & creation


• Bean scopes
• Bean lifecycle

These three topics are strongly connected in Spring Framework.


Understanding them together will help you explain how Spring manages objects internally during your
review meeting.

We’ll cover them in this order:

Bean Definition & Creation

[Link] Page 21 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Bean Scopes
Bean Lifecycle

1. Bean Definition & Creation


1.1 What is a Bean?
In Spring:

A Bean is simply a Java object that is created and managed by the Spring Container.

Example:

Java

@Component
class Engine {
}

Here Engine becomes a Spring Bean because the container manages it.

The container responsible for managing beans is usually ApplicationContext.

1.2 What is a Bean Definition?


Before creating a bean, Spring needs metadata describing the bean.

This metadata is called a Bean Definition.

A Bean Definition contains information like:

Bean class
Bean name (id)
Scope
Dependencies
Initialization method
Destruction method

Example metadata (conceptually):

Bean Definition
----------------------
Bean Name: engine
Class: Engine
Scope: Singleton
Dependencies: None
Init Method: init()
Destroy Method: destroy()

Spring stores this information internally using the class:

BeanDefinition

1.3 Ways to Define Beans


Spring supports three main ways to define beans.

1. XML Configuration (Old Way)

[Link] Page 22 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Example:

XML

<bean id="engine" class="[Link]"/>

<bean id="car" class="[Link]">


<property name="engine" ref="engine"/>
</bean>

Spring reads this configuration and creates beans.

2. Annotation-Based Configuration (Most Used)


Example:

Java

@Component
class Engine {
}

Java

@Component
class Car {

@Autowired
Engine engine;

Spring scans the package and registers these as beans.

Common annotations:

@Component
@Service
@Repository
@Controller

3. Java Configuration
Using @Configuration and @Bean .

Example:

Java

@Configuration
class AppConfig {

@Bean
Engine engine(){
return new Engine();
}
}

Here Spring registers Engine as a bean.

1.4 Bean Creation Process

[Link] Page 23 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

When a Spring application starts, the container performs these steps:

Start Application

Load Configuration

Scan Classes

Create Bean Definitions

Instantiate Beans

Inject Dependencies

Beans Ready to Use

Example:

Java

@Component
class Car {

@Autowired
Engine engine;

Spring does internally:

Create Engine Bean


Create Car Bean
Inject Engine into Car

2. Bean Scopes
Now we discuss how long a bean lives inside the container.

Bean Scope defines the lifecycle and visibility of a bean.

Types of Bean Scopes


Spring supports several scopes.

1. Singleton Scope (Default)


This is the default scope in Spring.

Definition:

Only one instance of the bean exists in the container.

Example:

Java

@Component
@Scope("singleton")
class Engine {
}

[Link] Page 24 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Behavior:

Container

Single Engine Object

Shared across application

All classes receive the same instance.

2. Prototype Scope
Definition:

A new bean instance is created every time it is requested.

Example:

Java

@Component
@Scope("prototype")
class Engine {
}

Behavior:

Request 1 → new Engine


Request 2 → new Engine
Request 3 → new Engine

Every request gets a different object.

3. Request Scope (Web Applications)


One bean instance per HTTP request.

Example:

User Request 1 → Bean Instance 1


User Request 2 → Bean Instance 2

4. Session Scope (Web Applications)


One bean instance per user session.

Example:

User A Session → Bean Instance A


User B Session → Bean Instance B

5. Application Scope
One bean instance for the entire web application.

3. Bean Lifecycle

[Link] Page 25 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Bean lifecycle describes how a bean is created, initialized, used, and destroyed.

Complete Bean Lifecycle


Inside Spring Framework, the lifecycle is:

Bean Definition Loaded



Bean Instantiation

Dependency Injection

BeanPostProcessor (Before Init)

Initialization

Bean Ready to Use

Bean Destruction

3.1 Step-by-Step Lifecycle


Step 1: Bean Instantiation

Spring creates the object.

Example:

Engine engine = new Engine();

Step 2: Dependency Injection

Dependencies are injected.

Example:

Car → Engine injected

Step 3: Bean Post Processor (Before Init)

Spring allows custom processing before initialization.

Handled by:

BeanPostProcessor

Step 4: Initialization

Custom initialization logic runs.

Example:

Java

[Link] Page 26 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

@PostConstruct
public void init(){
[Link]("Bean initialized");
}

Step 5: Bean Ready

Now the bean is fully usable.

Step 6: Destruction

When the container shuts down, destruction methods run.

Example:

Java

@PreDestroy
public void destroy(){
[Link]("Bean destroyed");
}

3.2 Lifecycle Methods Example


Example bean:

Java

@Component
class Engine {

@PostConstruct
public void init(){
[Link]("Engine initialized");
}

@PreDestroy
public void destroy(){
[Link]("Engine destroyed");
}
}

Lifecycle flow:

Create Engine

Inject Dependencies

@PostConstruct

Bean Ready

Application Running

@PreDestroy

4. Quick Review Summary (Very Important for Meeting)


Bean

Object managed by the Spring container.

[Link] Page 27 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Bean Definition

Metadata describing the bean configuration.

Bean Scope

Defines how many instances of a bean exist.

Common scopes:

Singleton (default)
Prototype
Request
Session
Application

Bean Lifecycle

Instantiation
Dependency Injection
Initialization
Usage
Destruction

5. Very Common Review Questions


Q1: What is a Bean?

A bean is an object managed by the Spring IoC container.

Q2: What is Bean Scope?

Bean scope defines the lifecycle and number of bean instances in the container.

Q3: What is the default bean scope?


Singleton

Q4: What is Bean Lifecycle?


The lifecycle describes the process of bean creation, initialization, usage, and destruction in the Spring
container.

If you want, I can also explain two extremely important Spring Core topics that reviewers often ask
next:

✔ ApplicationContext vs BeanFactory (very commonly asked)


✔ @Component, @Service, @Repository, @Controller (stereotype annotations)

These are very common review questions in Spring training programs.

[Link] Page 28 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Stereotype annotations
o @Component
o @Service
o @Repository
o @Controller

These annotations are called Stereotype Annotations in Spring Framework.


They are extremely important because they tell Spring:

“This class should be managed by the Spring container as a Bean.”

Your mentors often ask this because it shows whether you understand Spring architecture layers.

1. What Are Stereotype Annotations?


Stereotype annotations are special annotations used to mark a class as a Spring-managed component.

When Spring starts, it performs Component Scanning and automatically creates beans for these classes.

The main stereotype annotations are:

@Component
@Service
@Repository
@Controller

All of them are specialized versions of @Component .

2. Why Do We Need Stereotype Annotations?


Before annotations, Spring used XML configuration.

Example:

XML

<bean id="userService" class="[Link]"/>

This became difficult for large projects.

So Spring introduced annotations to automatically register beans.

Instead of XML, we write:

Java

@Service
class UserService {
}

Spring automatically registers it as a bean in the container.

[Link] Page 29 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

3. How Component Scanning Works


Spring scans packages for classes marked with stereotype annotations.

Example:

Java

@SpringBootApplication
@ComponentScan("[Link]")

Process:

Application Starts

Spring scans package

Finds @Component, @Service, etc.

Creates Beans

Stores them in IoC container

4. @Component
Definition
@Component is the base stereotype annotation.

It tells Spring:

“This class is a Spring-managed component.”

Example

Java

@Component
class Engine {

public void start(){


[Link]("Engine started");
}

Spring automatically creates a bean:

engine → Engine object

When to Use

Use @Component for general-purpose classes.

Example:

utility classes
helper classes

[Link] Page 30 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

configuration helpers

5. @Service
Definition

@Service marks a class as a service layer component.

Service layer contains business logic.

Example

Java

@Service
class UserService {

public String getUser(){


return "User Data";
}

Layer Architecture
Typical Spring architecture:

Controller

Service

Repository

Database

Service sits between Controller and Repository.

Why not just use @Component?

Technically you could, but @Service provides semantic meaning.

It tells developers:

This class contains business logic

6. @Repository
Definition

@Repository marks a class as a data access layer component.

This layer interacts with the database.

Example

[Link] Page 31 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Java

@Repository
class UserRepository {

public String getUserFromDB(){


return "User from DB";
}

Special Feature

@Repository provides automatic exception translation.

It converts database exceptions into Spring exceptions.

Example:

SQLException

DataAccessException

This makes error handling easier.

7. @Controller
Definition
@Controller marks a class as a web controller.

Controllers handle HTTP requests in web applications.

Usually used in Spring MVC.

Example

Java

@Controller
class UserController {

@Autowired
UserService userService;

public String getUser(){


return [Link]();
}

Flow:

Client Request

Controller

Service

Repository

Database

[Link] Page 32 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

8. Full Example of All Layers


Example structure:

UserController
UserService
UserRepository

Controller

Java

@Controller
class UserController {

@Autowired
UserService service;

Service

Java

@Service
class UserService {

@Autowired
UserRepository repository;

Repository

Java

@Repository
class UserRepository {

Spring automatically creates three beans and connects them using Dependency Injection.

9. Relationship Between Them


Important concept:

@Component

|
--------------------------------
| | |
@Service @Repository @Controller

All these annotations are specializations of @Component .

So they are detected during component scanning.

[Link] Page 33 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

10. Advantages of Stereotype Annotations


1. Automatic Bean Creation

No need to manually configure beans.

2. Better Code Organization

Each layer has a specific annotation.

3. Cleaner Configuration
No XML configuration required.

4. Easier Maintenance
Clear separation of concerns.

11. Very Important Review Question


Q1: What are stereotype annotations?

Stereotype annotations are special annotations used to mark classes as Spring-managed components so
they can be automatically detected during component scanning.

Q2: What are the main stereotype annotations?


@Component

@Service

@Repository

@Controller

Q3: What is the difference between them?


Annotation Layer

@Component Generic component

@Service Business logic layer

@Repository Data access layer

@Controller Web layer

Q4: Are @Service and @Repository different from @Component?


They are specialized forms of @Component , mainly used for better code readability and layer
identification.

12. One-Line Summary

[Link] Page 34 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Stereotype annotations mark classes as Spring beans and identify their role in the application
architecture.

Since you finished almost all Spring Core fundamentals, the next topics mentors often ask after
this are:

@Autowired and dependency resolution


ApplicationContext vs BeanFactory
Component Scanning
Spring Configuration ( @Configuration , @Bean )

If you want, I can also give you a “10 most common Spring Core review questions” list that mentors
usually ask trainees.
It will help you prepare answers confidently for your review meeting.

• Configuration types
o XML configuration
o Java configuration
o Annotation configuration

In Spring Framework, the container needs instructions to know:

Which objects to create


How to create them
How to connect them (dependencies)

These instructions are called Spring Configuration.

Spring supports three main configuration types:

XML Configuration
Java Configuration
Annotation Configuration

Understanding these is important because they explain how beans are registered in the Spring
Container (usually an ApplicationContext).

1. What is Spring Configuration?


Definition

Spring configuration is the process of defining beans and their dependencies so the Spring

[Link] Page 35 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

container can create and manage them.

Configuration tells Spring:

Which class → becomes a bean


How beans → are connected
What scope → they use
What lifecycle → they follow

2. XML Configuration (Old Traditional Way)


Before annotations existed, Spring applications were configured using XML files.

Spring reads the XML file and creates beans accordingly.

Example XML Configuration


[Link]

XML

<beans>

<bean id="engine" class="[Link]"/>

<bean id="car" class="[Link]">


<property name="engine" ref="engine"/>
</bean>

</beans>

Java Classes

Java

class Engine {
}

Java

class Car {

private Engine engine;

public void setEngine(Engine engine){


[Link] = engine;
}

What Spring Does Internally

[Link] Page 36 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Read [Link]

Create Engine Bean

Create Car Bean

Inject Engine into Car

Loading XML Configuration

Java

ApplicationContext context =
new ClassPathXmlApplicationContext("[Link]");

Spring container loads the XML file and creates beans.

Advantages
Explicit configuration
Easy to visualize bean relationships

Disadvantages
Too much XML
Hard to maintain in large applications
Not type-safe

Because of these issues, XML configuration is rarely used in modern Spring Boot applications.

3. Annotation Configuration (Most Common Today)


Spring introduced annotations to simplify configuration.

Annotations allow developers to declare beans directly in classes.

Common annotations include:

@Component
@Service
@Repository
@Controller

Example

Engine

Java

@Component
class Engine {

[Link] Page 37 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Car

Java

@Component
class Car {

@Autowired
Engine engine;

Spring automatically detects these beans using component scanning.

Component Scanning
Spring scans packages to find annotations.

Example:

Java

@ComponentScan("[Link]")

Process:

Application Starts

Spring scans package

Finds annotated classes

Creates Beans

Injects dependencies

Advantages

✔ Less configuration
✔ Cleaner code
✔ Easy dependency injection
✔ Better readability

4. Java Configuration
Java configuration uses Java classes instead of XML to define beans.

It is done using:

@Configuration
@Bean

Example

Configuration Class

Java

[Link] Page 38 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

@Configuration
class AppConfig {

@Bean
public Engine engine(){
return new Engine();
}

@Bean
public Car car(){
return new Car(engine());
}

Java Classes

Java

class Engine {
}

Java

class Car {

private Engine engine;

public Car(Engine engine){


[Link] = engine;
}

Starting the Container

Java

ApplicationContext context =
new AnnotationConfigApplicationContext([Link]);

Spring reads the configuration class and creates beans.

What Happens Internally

Load AppConfig

Call engine()

Create Engine Bean

Call car()

Inject Engine into Car

5. Comparison of Configuration Types

[Link] Page 39 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Configuration Type Description Usage Today

XML Configuration Beans defined in XML file Rare

Annotation Configuration Beans declared using annotations Very common

Java Configuration Beans defined using Java methods Common

6. Modern Spring Boot Approach


In modern Spring Boot apps, configuration usually combines:

Annotations
+
Java Configuration

Example:

@SpringBootApplication

This annotation internally includes:

@Configuration
@ComponentScan

@EnableAutoConfiguration

So Spring automatically configures the application.

7. Configuration Flow Inside Spring


When application starts:

Load Configuration

Create Bean Definitions

Initialize Spring Container

Create Beans

Inject Dependencies

Application Ready

8. Very Common Review Questions


Q1: What are the configuration types in Spring?

Spring supports three main configuration types:

1. XML configuration
2. Annotation configuration
3. Java configuration

Q2: Which configuration is most commonly used today?

Annotation configuration with Java configuration, especially in Spring Boot.

[Link] Page 40 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Q3: What is @Configuration ?

@Configuration indicates that a class contains bean definitions for the Spring container.

Q4: What is @Bean ?

@Bean tells Spring that the method returns an object that should be managed as a Spring bean.

9. One-Line Summary
Spring configuration defines how beans are created and wired inside the Spring container using
XML, annotations, or Java classes.

Since you finished almost the entire Spring Core Module, the last thing that will help you in your
review meeting is usually:

Difference between BeanFactory and ApplicationContext


10–15 tricky Spring Core questions mentors ask

If you want, I can also give you a “complete Spring Core review cheat sheet” so you can revise
everything in 5 minutes before your review.
• @Autowired, @Qualifier, @Primary

These annotations are used for Dependency Injection in Spring Framework.


They help Spring decide which dependency to inject when multiple beans are available.

The three important annotations are:

@Autowired
@Qualifier
@Primary

They work together to resolve dependency conflicts.

1. @Autowired
Definition
@Autowired is used to automatically inject dependencies from the Spring container.

Instead of manually creating objects, Spring finds the required bean and injects it.

Example

Engine Class

Java

@Component
class Engine {
}

Car Class

[Link] Page 41 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Java

@Component
class Car {

@Autowired
Engine engine;

What Spring Does

When the application starts:

Create Engine Bean


Create Car Bean
Inject Engine → Car

Spring searches for a bean of type Engine and injects it.

Where @Autowired Can Be Used


Spring allows dependency injection in three places.

Field Injection

Java

@Autowired
Engine engine;

Constructor Injection (Recommended)

Java

@Component
class Car {

private Engine engine;

@Autowired
public Car(Engine engine){
[Link] = engine;
}

Modern Spring can even omit @Autowired if there is only one constructor.

Setter Injection

Java

@Autowired
public void setEngine(Engine engine){
[Link] = engine;
}

[Link] Page 42 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

2. Problem When Multiple Beans Exist


Now imagine this situation.

Two Engine implementations exist.

DieselEngine

Java

@Component
class DieselEngine implements Engine {
}

ElectricEngine

Java

@Component
class ElectricEngine implements Engine {
}

Car Class

Java

@Component
class Car {

@Autowired
Engine engine;

Spring now sees:

DieselEngine
ElectricEngine

Both match type Engine.

Spring gets confused and throws an error:

NoUniqueBeanDefinitionException

This means:

Spring found multiple beans of the same type.

To solve this we use @Qualifier or @Primary.

3. @Qualifier
Definition
@Qualifier tells Spring exactly which bean should be injected.

[Link] Page 43 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Example

DieselEngine

Java

@Component("dieselEngine")
class DieselEngine implements Engine {
}

ElectricEngine

Java

@Component("electricEngine")
class ElectricEngine implements Engine {
}

Car Class

Java

@Component
class Car {

@Autowired
@Qualifier("dieselEngine")
Engine engine;

What Happens

Spring will inject:

DieselEngine

instead of ElectricEngine.

4. @Primary
Definition
@Primary marks a bean as the default bean when multiple beans exist.

Example

DieselEngine

Java

@Component
@Primary
class DieselEngine implements Engine {
}

[Link] Page 44 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

ElectricEngine

Java

@Component
class ElectricEngine implements Engine {
}

Car Class

Java

@Component
class Car {

@Autowired
Engine engine;

What Happens

Spring automatically injects:

DieselEngine

because it is marked as Primary.

5. Difference Between @Qualifier and @Primary


Annotation Purpose

@Autowired Automatically inject dependency

@Qualifier Specify exactly which bean to inject

@Primary Set default bean when multiple beans exist

6. Priority Rule in Spring


When Spring injects dependencies, it follows this order:

@Qualifier
@Primary
Bean Name
Type Matching

Example:

@Qualifier present → highest priority

7. Real Application Example


Typical Spring Boot architecture:

[Link] Page 45 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Controller

Service

Repository

Example:

Repository

Java

@Repository
class UserRepository {
}

Service

Java

@Service
class UserService {

@Autowired
UserRepository repository;

Spring automatically injects UserRepository into UserService .

8. Common Mistake Developers Make


Many beginners think:

@Autowired = create object

This is incorrect.

Correct understanding:

Spring Container creates objects


@Autowired only injects them

9. Very Common Review Questions


Q1: What is @Autowired?

@Autowired automatically injects dependencies from the Spring IoC container.

Q2: When do we use @Qualifier?

When multiple beans of the same type exist and we want to specify which bean should be injected.

Q3: What does @Primary do?

@Primary marks a bean as the default candidate for dependency injection.

[Link] Page 46 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Q4: Which has higher priority?

@Qualifier > @Primary

10. One-Line Summary

@Autowired → inject dependency


@Qualifier → choose specific bean
@Primary → default bean

Since you have now covered almost the entire Spring Core module, if you want I can also give you:
A complete Spring Core architecture diagram
15 tricky questions mentors ask in review meetings
A 5-minute revision sheet for everything you studied

That will make your review meeting much easier to handle.

Summarise the whole chat for revision

Here is a clean revision summary of your entire Spring Core Module 1.


You can revise this 5–10 minutes before your review meeting.

Everything here is based on Spring Framework fundamentals.

1. IoC (Inversion of Control)


Definition
IoC is a design principle where control of object creation is given to the Spring container instead of the
application code.

Normal Java:

Class creates its own objects

Spring IoC:

Spring Container creates objects

Purpose
Reduce tight coupling
Improve maintainability
Simplify dependency management

Example Concept

Car → depends on → Engine

[Link] Page 47 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Instead of Car creating Engine , Spring injects it.

2. Dependency Injection (DI)


Definition

Dependency Injection means providing dependencies to a class instead of the class creating them
itself.

Spring implements IoC using DI.

Types of DI
Type Description

Constructor Injection Dependency passed via constructor (recommended)

Setter Injection Dependency injected using setter method

Field Injection Dependency injected directly into field

Example:

Java

@Component
class Car {

@Autowired
Engine engine;

3. Spring Container
The Spring Container is responsible for:

Creating beans
Managing dependencies
Handling lifecycle
Configuring application components

The most commonly used container is:

ApplicationContext

Types of Containers
Container Description

BeanFactory Basic container

ApplicationContext Advanced container (commonly used)

Container Flow

[Link] Page 48 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Start Application

Load Configuration

Create Beans

Inject Dependencies

Application Ready

4. Bean Definition & Creation


Bean
A bean is an object managed by the Spring container.

Example:

Java

@Component
class Engine {
}

Bean Definition
Bean definition contains metadata such as:

Class name
Bean id
Scope
Dependencies
Lifecycle methods

Spring stores this internally using BeanDefinition metadata.

Ways to Define Beans


Method Description

XML Beans defined in XML file

Annotation Beans declared using annotations

Java Config Beans defined using Java methods

5. Bean Scopes
Bean scope defines how many instances of a bean exist in the container.

Common Scopes

[Link] Page 49 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Scope Description

Singleton One instance for entire application (default)

Prototype New instance every request

Request One instance per HTTP request

Session One instance per user session

Application One instance per web application

Example:

Java

@Scope("prototype")

6. Bean Lifecycle
The lifecycle describes how beans are created and destroyed.

Lifecycle Steps

Load Bean Definition



Bean Instantiation

Dependency Injection

Initialization

Bean Ready

Destruction

Lifecycle Annotations

@PostConstruct → runs after bean initialization


@PreDestroy → runs before bean destruction

7. Stereotype Annotations
These annotations mark classes as Spring-managed components.

Main stereotype annotations:

@Component
@Service
@Repository
@Controller

Purpose

[Link] Page 50 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Annotation Layer

@Component Generic component

@Service Business logic layer

@Repository Data access layer

@Controller Web layer

All of them are specialized forms of @Component .

8. Configuration Types
Spring supports three configuration styles.

1. XML Configuration
Old style using XML files.

Example:

XML

<bean id="engine" class="Engine"/>

2. Annotation Configuration

Uses annotations like:

@Component
@Autowired
@Service

Most common in modern applications.

3. Java Configuration

Uses Java classes for configuration.

Annotations used:

@Configuration
@Bean

Example:

Java

@Configuration
class AppConfig {

@Bean
Engine engine(){
return new Engine();
}

[Link] Page 51 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

9. @Autowired, @Qualifier, @Primary


These annotations help inject and resolve dependencies.

@Autowired

@Autowired automatically injects dependencies.

Example:

Java

@Autowired
Engine engine;

Problem

If multiple beans exist:

DieselEngine
ElectricEngine

Spring gets confused.

@Qualifier

@Qualifier specifies which bean to inject.

Example:

Java

@Autowired
@Qualifier("dieselEngine")
Engine engine;

@Primary

@Primary marks a bean as the default bean.

Example:

Java

@Primary
class DieselEngine

Priority Order

@Qualifier > @Primary > Type Matching

10. Complete Spring Core Flow

[Link] Page 52 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

Application Starts

Spring Container Starts

Configuration Loaded

Beans Created

Dependencies Injected

Bean Lifecycle Managed

Application Runs

5-Minute Revision (Quick Cheat Sheet)

IoC → Spring controls object creation


DI → Spring injects dependencies

Spring Container → manages beans

Bean → object managed by Spring

Bean Scope → lifecycle of bean


(default = singleton)

Bean Lifecycle →
Instantiation → Injection → Init → Destroy

Stereotype Annotations →
@Component
@Service
@Repository
@Controller

Configuration Types →
XML
Annotations
Java Configuration

@Autowired → inject dependency


@Qualifier → choose specific bean
@Primary → default bean

Tip for your review meeting:

Mentors usually ask questions in this order:

What is IoC and DI?


What is the Spring Container?
What is a Bean?
What are Bean Scopes?
Explain @Autowired / @Qualifier / @Primary.

If you can explain these clearly, you’ve mastered Spring Core basics.

If you want, I can also give you “20 Spring Core review questions mentors commonly ask trainees” so
you can practice answering them before your meeting.

[Link] Page 53 of 54
Spring Core Review Prep 18/03/26, 1:11 PM

[Link] Page 54 of 54

You might also like