Skip to main content

πŸ₯Š @Component vs @Configuration — Not Just Cousins in Spring! 😲

 πŸ§  Ever looked at these two annotations and thought:

“Aren’t they doing the same thing?”
Welcome to the club. I had the same confusion until... I went deep down the Spring rabbit hole πŸ•³️πŸ‡

Let’s clear this once and for all — with real differences, examples, gotchas, and even a few bad jokes along the way 😎


🌟 The Basic Definitions

Annotation Meaning
@Component A general-purpose stereotype indicating a class is a Spring-managed bean
@Configuration A specialized class used to declare beans via @Bean methods

πŸ’‘ Both register beans with Spring — but what happens behind the scenes is where it gets spicy 🌢️


πŸ€” But Aren’t They Both Just “Beans”?

Short answer: Yes.
Long answer: It’s complicated — like your last relationship πŸ’”.


⚙️ INTERNAL MAGIC: The Real Difference

1. @Configuration Uses CGLIB Proxy for Singleton πŸ’«

When you mark a class with @Configuration, Spring uses CGLIB subclassing (AOP-style proxying) to make sure all @Bean methods return the same singleton — even if called multiple times.

πŸ’£ Example:


@Configuration
public class MyConfig {

    @Bean
    public Engine engine() {
        return new Engine(); // always returns same Engine
    }

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


πŸ“Œ Result:
Spring intercepts engine() call inside car() and reuses the same singleton object.


2. @Component Doesn’t Use CGLIB Proxy 😐

If you do this:


@Component
public class MyConfig {

    @Bean
    public Engine engine() {
        return new Engine(); // 😡 This gets called multiple times!
    }

    @Bean
    public Car car() {
        return new Car(engine()); // Creates a new Engine every time
    }
}


πŸ’₯ Boom! Now car() and engine() use different objects — no proxying here.

🧠 This is why Spring recommends using @Configuration for bean factories, not @Component.


πŸ›‘️ Singleton Is Not Just a Pattern — It’s a Proxy Game

Without CGLIB proxying, Spring cannot guarantee singleton behavior across bean methods. That’s why:

  • @Configuration = Proxy-magic πŸͺ„ + Full bean lifecycle control
  • @Component = Regular class 🧱 with Spring bean creation only

πŸ•΅️‍♂️ Real-World Gotcha You Didn’t Know

❗ Changing @Configuration to @Component breaks singleton!

You might have seen this subtle bug in interviews or production:

You might have seen this subtle bug in interviews or even production:

@Configuration
public class MyConfig {
   ...
}

➡️ Someone changes it to:

@Component
public class MyConfig {
   ...
}

🎯 Guess what? It still works… but beans aren’t singleton anymore 😱




✅ Why We Use @Component — And How Spring Knows What to Wire πŸ”Œ

Let’s say you wrote a simple utility class like this:


@Component public class EmailUtil { public void send(String to, String body) { System.out.println("Sending email to " + to); } }

Now… how does Spring know this class even exists? And how do we use it?


πŸ“Œ Step 1: Mark with @Component

This tells Spring:

“Hey, please manage this class. Make an object, keep it ready, I’ll be needing it.” πŸ˜„

Spring adds it to the ApplicationContext during startup (if it's in a scanned package).


πŸ“Œ Step 2: Inject It Using @Autowired or Constructor Injection


@Service public class NotificationService { private final EmailUtil emailUtil; @Autowired public NotificationService(EmailUtil emailUtil) { this.emailUtil = emailUtil; } public void notifyUser() { emailUtil.send("me@example.com", "Your order is shipped!"); } }

Now Spring will auto-wire EmailUtil wherever it's needed!


πŸ”„ So the Flow Looks Like This:

  1. You annotate EmailUtil with @Component

  2. Spring finds it via @ComponentScan during startup πŸ”

  3. You use @Autowired (or constructor injection) to inject it into another class 🚚

  4. Spring sees the request and wires the singleton instance of EmailUtil πŸͺ„


🀯 What If You Don’t Annotate It with @Component?

Then Spring won’t even know it exists
→ You'll get a NoSuchBeanDefinitionException when you try to inject it.


🎭 Use Cases — When to Use What?

Use This For... Annotation
Declaring beans with @Bean @Configuration ✅
General Spring component scan @Component ✅


πŸ˜‚ Funny Analogy

Imagine @Component is like a coffee shop πŸͺ.
You order coffee ☕, and they make a new one each time.
But @Configuration is like your mom’s kitchen 🏠 —
She remembers what you ordered last week and says:

"Son, manage with one cup... memory is limited here too, like our heap space!" πŸ§ πŸ’‍♀️


🧠 Summary — The Final Showdown

Feature @Component @Configuration
Spring Bean Registration
Proxy Bean Method Calls ✅ (CGLIB)
Ensures Singleton
Use with @Bean methods 🚫 Avoid ✅ Recommended

🎨 Bonus: Colorful Icons for Memory 🧠

  • πŸ”§ @Component = Generic Tool

  • πŸ—️ @Configuration = Master Builder with Memory

  • πŸ§ͺ @Bean = Custom-Made Ingredient

  • πŸ”‚ CGLIB = Behind-the-scenes Repeater


🀹 Wrapping Up

So next time someone says “@Component and @Configuration are same,”
just drop this truth bomb πŸ’£:

Only one of them respects Singleton. The other one? It’s freelancing 😎

πŸ’¬ Got more such hidden Spring secrets or confusion?
Drop a comment — I love exploring the “whys” behind the “hows”!

Comments

Popular posts from this blog

🐱 Tomcat vs ⚡ Netty – Which One Should You Use?

🐱 Tomcat vs ⚡ Netty – Which One Should You Use? So recently I got curious about this too πŸ€”. Everywhere in Spring Boot tutorials we see Tomcat . Then suddenly while exploring Spring WebFlux , the name Netty pops up. And I was like – “Wait, who’s this Netty guy trying to replace Tomcat?” πŸ˜… Let’s break it down with real-time examples , icons , and fun comparisons . 🐱 Tomcat – The Traditional Web Server Type: Servlet Container (blocking I/O) World: Used with Spring MVC Style: Thread-per-request model πŸ‘©‍πŸ’» Pros: Stable, widely used, battle-tested Cons: Struggles with huge concurrent connections πŸ‘‰ Example in real life: Tomcat is like a restaurant with fixed waiters 🍴. - Each customer = one thread/waiter - If too many customers come in at once → waiters run out → customers wait outside πŸšͺ ⚡ Netty – The Reactive Rockstar Type: Asynchronous Event-Driven Network Framework World: Default for Spring WebFlux Style: Event-lo...

🎭 Spring’s Secret: Why @Transactional & Friends Betray You Silently

πŸ’‘ Lesson Learned — Not a Prod Bug, But a Real Pain No, this wasn’t a production outage. Nobody screamed at me. But I sat for 3 hours wondering: “Why the heck is my @Transactional not rolling back!?” 😡‍πŸ’« “Why is Redis cache not working?” 🀯 Turned out, the issue was one silent villain: 🧱 Self-invocation 🀷 What Is @Transactional ? If you're new: @Transactional = Tells Spring to start a DB transaction when a method is called. It’ll commit if everything’s okay. It’ll rollback if something fails. 🧠 Think of it like wrapping your code in: try { beginTransaction(); // your logic commit(); } catch(Exception e) { rollback(); } πŸ•΅️ Real-Life Analogy — The Gateway Community 🏘️ Let me tell you about my society — it has a strict watchman at the gate. Here’s how it works: πŸ›‚ Watchman = Spring Proxy 🏠 Your apartment = Your service class πŸšͺ Your room = A method inside that class πŸƒ Scenario 1: Outsider Visits Your friend from outside...

🌟 My Journey – From Zero to Senior Java Tech Lead 🌟

 There’s one thing I truly believe… If I can become a Java developer, then anyone in the world can. πŸ’― Sounds crazy? Let me take you back. πŸ•“ Back in 2015… I had zero coding knowledge . Not just that — I had no interest in coding either. But life has its own plans. In 2016, I got a chance to move to Bangalore and joined a Java course at a training center. That’s where it all started — Every day, every session made me feel like: "Ohhh! Even I can be a developer!" That course didn’t just teach Java — it gave me confidence . πŸ§ͺ Two Life-Changing Incidents 1️⃣ The Interview That Wasn't Planned Halfway through my course, I had to urgently travel to Chennai to donate blood to a family member. After that emotional rollercoaster, I found myself reflecting on my skills and the future. The next day, as I was preparing for my move to Bangalore to complete the remaining four months of my course, I randomly thought — "Let me test my skills... let me just see...