🫘 What is a Bean?
Think of a Bean as an object (a real Java class) that Spring takes care of for you.
🧠 Simple Analogy:
Imagine you own a coffee shop.
Normally, you’d hire the staff, buy the coffee machine, buy the cups—you do everything yourself.
But in the Spring world, it’s like you have a manager (Spring Container) who says:
“Tell me what you need, and I’ll arrange everything for you. You just sit back and enjoy.”
So if your application needs a class like CoffeeMaker, Spring will:
Create an object of it (i.e., a Bean),
Give it everything it needs to work (like water, coffee powder, cups—called dependencies),
And give you the ready-to-use CoffeeMaker.
🔄 What is Inversion of Control (IoC)?
It literally means: You don’t control how things are created anymore—Spring does.
In traditional code:
CoffeeMaker cm = new CoffeeMaker(new Filter(), new Grinder());
➡️ You are in control. You create the object and its parts.
But in IoC:
@Autowired
CoffeeMaker cm;
➡️ You just say, "I need a CoffeeMaker", and Spring gives it to you fully set up.
🧪 What is Dependency Injection (DI)?
It’s how Spring gives you what you need.
Example: If your CoffeeMaker needs a Filter, Spring will inject a Filter object into it automatically.
🔁 Summary in Simple Words
✅ What Are Annotations?
In simple words:
Annotations are special tags in Java (starting with @) that give extra information to the Java compiler or Spring framework about how to treat your code.
Example:
This tells Spring: “Please inject a dependency here.”
🧠 Real-life Analogy
Think of annotations like sticky notes on your objects:
🎯 Basic Spring Annotations for Bean Management
🔧 Full Example using Annotations
Let’s use the coffee shop analogy again but now with annotations.
1️⃣ Dependency: Filter.java
import org.springframework.stereotype.Component;
Here, @Component tells Spring to create and manage a Bean of Filter.
2️⃣ Main Bean: CoffeeMaker.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component = Make this a Bean
@Autowired = Spring, please give me the Filter
3️⃣ Main App: MainApp.java
✅ Output
Brewing coffee using: Steel Filter
🚀 Recap
🧱 What is "Scope"?
In real life, scope means how long something lives and who gets to use it.
In Spring, scope means:
"How many copies of an object do you want Spring to create and who should get it?"
Spring manages Java objects (called Beans) and gives them to you when needed. But you can tell Spring how to manage those objects using scopes.
🧠 Real-Life Examples for Each Scope
1️⃣ singleton — Default
🧍♂️ One shared object for everyone.
Like one printer in an office — everyone uses the same one.
Spring creates one CoffeeMaker, and everyone shares it.
Fast and memory-saving.
🧪 Example:
2️⃣ prototype — New every time
🎁 One new object every time you ask.
Like using a new paper cup every time you drink coffee.
Spring creates a new CoffeeMaker every time someone asks.
Useful when objects need to be independent or carry different data.
🧪 Example:
3️⃣ request — One per web request
🌐 One object per HTTP request.
Like a shopping cart that exists only while you’re browsing a website. Once done, it disappears.
Spring gives one CoffeeMaker per web request, and it's gone after that.
🧪 Example:
(Used only in web apps)
4️⃣ session — One per user login session
🔐 One object per user session.
Like a Netflix account — it remembers what you're watching until you log out.
Spring creates one CoffeeMaker per user, and it stays until the user logs out or session ends.
🧪 Example:
(Used in web apps only)
5️⃣ globalSession — Legacy scope
🏛️ Like a shared lobby for everyone in a government building.
Mostly used in old-style portals (you won’t need this in most apps).
Ignore unless you're doing advanced/legacy work.
🧪 Example:
🗂️ Summary Table (in Lehman’s terms)
🔧 How to Tell Spring About Scope?
Just add @Scope("...") on your class like this:
Note: @Scope
can be added for @Bean
, @Component
, @Service
, @Controller
, @RestController
, etc.
What is @SpringBootApplication?
It's a shortcut annotation that tells Spring Boot:
“Hey! This is the starting point of my application. Please auto-configure everything for me.”
📦 Full Definition
@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan
So when you write:
It secretly means you're using three annotations at once.
🧠 Lehman’s Analogy
Imagine you’re opening a restaurant.
@Configuration = Your kitchen blueprint (how things are laid out)
@ComponentScan = Your hiring manager, who finds all your staff (classes with @Component, @Service, etc.)
@EnableAutoConfiguration = Your smart assistant, who says:
"Oh, you added a coffee machine? I’ll automatically plug it in and set it up!"
Together, @SpringBootApplication = A restaurant manager who knows:
What kitchen setup to use (@Configuration)
Who the staff is (@ComponentScan)
How to auto-setup things (@EnableAutoConfiguration)
🧱 Let’s Break it Down Step by Step
✅ 1. @Configuration
“This class contains instructions on how to create beans manually if needed.”
Example:
💡 Without this, Spring won't know how to create things you manually define.
✅ 2. @EnableAutoConfiguration
“Spring, look at my classpath and automatically configure things based on what you find.”
Example:
If Spring sees H2 Database in your project:
✅ It auto-configures an H2 connection.If you add Spring Web:
✅ It auto-creates an embedded Tomcat server.
💡 This is what gives Spring Boot its magic — no XML, no manual setup!
✅ 3. @ComponentScan
“Look for all the Java classes in this package and its sub-packages that have annotations like @Component, @Service, @RestController, etc., and register them as beans.”
Without this, your @Component classes won’t be discovered.
✅ Final Example in Lehman's Code
When you run this:
🧰 Spring does 5 things:
Sees @SpringBootApplication → understands this is the main entry point.
Applies @Configuration → loads any manual beans if present.
Applies @ComponentScan → finds all classes with @Component, @Service, etc.
Applies @EnableAutoConfiguration → configures beans automatically (like database, web server).
Starts the embedded Tomcat server (if it's a web app).
🧾 Summary in Lehman's Table
🏷️ What is @Bean in Lehman's Terms?
@Bean means:
“Hey Spring, I want you to create and manage this object manually, even though it's not marked with @Component, @Service, etc.”
It’s like saying:
“This object is not from your usual hiring system (@ComponentScan). I’m bringing in an outside helper manually, so please manage it for me.”
🧠 Real-Life Analogy
Imagine your restaurant (Spring app) needs an external delivery guy (like Swiggy). He’s not your staff, but you still need him to bring coffee beans regularly.
You manually bring him in.
You want your manager (Spring) to still track and manage him.
This is where you say:
So now Spring knows:
➡️ “Ah! I need to manage this guy like I do for internal staff!”
💡 When is @Bean used in Spring MVC?
In Spring MVC, it's commonly used to manually create things like:
RestTemplate (for making HTTP API calls)
ModelMapper (for converting between DTOs and entities)
ObjectMapper (for custom JSON handling)
Custom ViewResolvers, Interceptors, Filters, etc.
✅ Common Use Case: RestTemplate Bean
⚙️ Why we need it:
Spring doesn’t provide RestTemplate automatically. You have to create it manually and let Spring manage it.
✅ Example Code (Step by Step)
1️⃣ Create the Bean Using @Bean
// AppConfig.java
🧠 Explanation:
@Configuration tells Spring this class provides setup instructions.
@Bean tells Spring: "Please create and manage this RestTemplate instance."
2️⃣ Use That Bean in a Controller
// CoffeeController.java
🧠 What happens here:
You ask Spring for a RestTemplate.
Spring says: “Ah, I already have that! I built it from @Bean config.”
Spring injects it into your controller like it does for @Service or @Repository.
🔁 What if I didn’t use @Bean?
You’d have to write:
RestTemplate restTemplate = new RestTemplate();
But this breaks Spring’s model — you’re doing manual work everywhere, losing benefits like:
Auto-injection
Centralized configuration
Custom settings (like timeouts or interceptors)
🔍 Summary Table
🧪 Output (Example)
If you visit http://localhost:8080/external-coffee, it will:
Use the RestTemplate Bean
Call an external API (https://api.sampleapis.com/coffee/hot)
Return the JSON response to your browser.
🔧 What is @Autowired in Spring?
@Autowired tells Spring:
"Hey Spring, please give me the object I need — don’t make me create it manually!"
It’s part of Dependency Injection, where Spring automatically gives you the right helper/tool/object (bean) your class needs.
🧠 Real-Life Analogy
Imagine you're a restaurant chef. You don’t buy vegetables, knives, or ingredients yourself.
You say:
“Give me a knife, give me onions.”
And your manager (Spring) makes sure they’re there when you need them.
That’s what @Autowired does — it auto-delivers dependencies to your code.
💡 Where Can You Use @Autowired?
✅ Step-by-Step Example (Field, Constructor, Setter)
Let’s build a simple app where a CoffeeMachine needs a Filter.
1️⃣ Create the Dependency Bean
// Filter.java
📌 @Component tells Spring: “Create a Filter bean.”
2️⃣ Field Injection (@Autowired on field)
// CoffeeMachine.java
🧠 Here:
Spring looks for a Filter bean.
Injects it into the filter field — no need to create it manually.
3️⃣ Constructor Injection (Recommended Way)
// CoffeeMachine.java
✅ Why is this best practice?
Works well with final fields.
Encourages immutability.
Easy to test.
4️⃣ Setter Injection
📌 Used when the dependency is optional or can change.
5️⃣ Main Application
🧪 Output
Brewing coffee with: Steel Filter
✅ Spring automatically injected the Filter into CoffeeMachine using @Autowired.
📝 Summary Table
❗ Common Pitfalls to Avoid
🧠 What Problem Does @Qualifier Solve?
Imagine you have two similar things (e.g., two types of bikes: Hero and Honda), and you ask Spring:
“Hey Spring, give me a bike.”
Spring will get confused because it sees two bikes and won’t know which one you want. That’s where @Qualifier helps — it lets you specify the name of the bean you want.
✅ Step-by-Step Example
📌 Use Case: Two different database connections (dummy examples)
Let’s simulate 2 DB connections: mysqlDataSource and postgresDataSource.
👣 Step 1: Create a DataSource Interface (or any type you want to inject)
public interface DataSource {
void connect();
}
👣 Step 2: Create Two Implementations
Here, both classes implement DataSource, and are annotated with @Component, but given different names using @Component("name").
👣 Step 3: Inject Specific Bean Using @Qualifier
👣 Step 4: Run the Spring Boot Application
🧩 Why @Qualifier is Important?
If you skip @Qualifier like this:
@Autowired
private DataSource dataSource;
Spring will throw an error like:
"No unique bean of type DataSource" – because it found two implementations and doesn’t know which one to inject.
✅ Summary
✅ Alternate: With Setter Injection
1. @Component — General Worker
💡 In Lehman’s Term:
"@Component is a general-purpose worker. You mark a class with this so Spring knows: 'Hey, create and manage this class object for me!'"
✅ Example:
Spring will now automatically create and manage this class as a bean.
🛠️ Specialized @Component Types
These are specific job roles (just like in an office, not all employees do the same job):
🧩 2. @Service — Business Logic Guy
💡 In Lehman’s Term:
"@Service is used when your class is handling core business logic, like calculations, processing rules, etc."
✅ Example:
🧩 3. @Repository — Database Worker (DAO)
💡 In Lehman’s Term:
"@Repository is a worker who talks to the database – for storing, retrieving, updating, deleting data."
✅ Example:
🔧 Also, Spring handles exceptions automatically in these classes (converts SQL exceptions into Spring exceptions).
🧩 4. @Controller — Web Gatekeeper
💡 In Lehman’s Term:
"@Controller handles web requests. It's the guy at the front desk who receives your HTTP requests and sends back the appropriate view (like HTML page)."
✅ Example:
🧩 5. @RestController — API Responder (JSON guy)
💡 In Lehman’s Term:
"@RestController is like @Controller, but instead of giving HTML pages, it gives back JSON or raw data."
It’s used when building REST APIs.
✅ Example:
This is the same as:
🧩 6. @Configuration — Blueprint Maker
💡 In Lehman’s Term:
"@Configuration is used for configuration or setup classes. It's like the architect or blueprint writer of the system."
You often combine it with @Bean methods to create and control beans manually.