DEV Community

gaurbprajapati
gaurbprajapati

Posted on

SPRING BOOT: @Configuration and @Bean — Complete Beginner Guide

🔹 1. What is Spring IoC (Inversion of Control)?

Before learning @Configuration or @Bean, you need to understand what IoC means.

✅ Simple Explanation:

Normally, in Java, you create objects using new keyword, like:

Database db = new Database();
Enter fullscreen mode Exit fullscreen mode

But in Spring, we don’t do that manually.

Instead, Spring creates and manages these objects for you — this is called the IoC Container (Inversion of Control Container).

You just tell Spring what objects (Beans) you need, and it creates and injects them automatically.


💡 Analogy:

Imagine you’re a chef. You need ingredients (objects) to cook a meal (application).
Instead of buying each ingredient manually, you tell your assistant (Spring) what you need.
Spring goes, buys them, prepares them, and gives them to you ready to use.

That assistant = Spring IoC Container
Ingredients = Beans


🔹 2. What is @Configuration?

✅ Definition:

@Configuration is a class-level annotation that tells Spring:

"This class contains one or more methods that define Beans."

So, Spring should scan this class and use it to create and manage beans in the IoC container.


🧠 Example:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public Database database() {
        return new Database("localhost", 3306);
    }

    @Bean
    public UserService userService() {
        return new UserService(database());
    }
}
Enter fullscreen mode Exit fullscreen mode

🧩 What’s happening here:

  • The class AppConfig is marked with @Configuration.
  • Inside it, we define two methods with @Bean.
  • When Spring starts, it runs these methods and stores the returned objects inside the ApplicationContext (Spring container).
  • Now, wherever you need Database or UserService, you don’t need new Database() — Spring injects them automatically.

⚙️ When to use @Configuration

Use @Configuration when:

  • You want to manually define beans in Java instead of XML.
  • You need to control how objects are created (custom constructors, conditions, etc.)
  • You are building library or reusable configuration modules.

🔹 3. What is @Bean?

✅ Definition:

@Bean is a method-level annotation used inside a @Configuration class to define a bean.

Each method annotated with @Bean tells Spring:

“The object returned by this method should be registered as a bean in the IoC container.”


🧠 Example:

@Bean
public EmailService emailService() {
    return new EmailService("smtp.gmail.com");
}
Enter fullscreen mode Exit fullscreen mode

When Spring sees this method, it calls it once, gets the EmailService object, and registers it in the container.


🧩 Why do we use @Bean?

Reason Explanation
🧱 Define custom beans You can define your own beans that are not automatically detected by @ComponentScan
⚙️ Full control You can control how beans are created, their dependencies, constructors, parameters
🔁 Integration You can define third-party library beans (like DataSource, ObjectMapper, etc.)
🧩 Custom logic Sometimes you need to initialize beans with special logic — @Bean is perfect for that

⚙️ When to use @Bean

Use @Bean when:

  • The class is not annotated with @Component, but you still want to register it as a bean.
  • You want to create beans conditionally or dynamically (e.g., based on environment or property).
  • You are integrating with external libraries that you can’t modify (like RestTemplate, ObjectMapper, etc.).

🔁 Example in Real Spring Boot Project

You often see code like this:

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, anywhere in your project, you can write:

@Autowired
private RestTemplate restTemplate;
Enter fullscreen mode Exit fullscreen mode

Spring will automatically inject it!


🔹 4. How @Bean and @Configuration Work in the Spring IoC Flow

Let’s see what happens behind the scenes:


⚙️ Step-by-Step Flow:

  1. Spring Boot starts (via @SpringBootApplication).
  2. Component scanning begins — Spring scans your package for:
  • @Component
  • @Service
  • @Repository
  • @Controller
  • @Configuration

    1. When Spring finds a class annotated with @Configuration, it:
  • Creates a proxy of it (using CGLIB).

  • Calls all @Bean methods only once.

    1. For each @Bean method:
  • Spring calls the method.

  • Takes the returned object.

  • Registers it as a bean in the IoC container.

    1. When another class requests that bean (@Autowired), Spring provides it from the container.

🔄 Diagram of Flow:

          +----------------------------+
          |  Spring Boot Application   |
          +-------------+--------------+
                        |
                        v
             [Component Scan Begins]
                        |
                        v
         +-----------------------------------+
         |  Finds @Configuration Class (AppConfig)  |
         +-----------------------------------+
                        |
                        v
           +-------------------------------+
           |   Create Proxy of AppConfig    |
           +-------------------------------+
                        |
                        v
          +-------------------------------+
          |   Call @Bean methods once      |
          |   (e.g., database(), userService())  |
          +-------------------------------+
                        |
                        v
       +--------------------------------------------+
       | Register each returned object as a Bean in |
       |         Spring IoC Container                |
       +--------------------------------------------+
                        |
                        v
           +-------------------------------+
           |   Beans ready for injection   |
           +-------------------------------+
                        |
                        v
          +--------------------------------+
          |  Other classes @Autowired them |
          +--------------------------------+
Enter fullscreen mode Exit fullscreen mode

🔹 5. Common Interview Questions

Question Answer
What’s the difference between @Bean and @Component? @Bean is used inside a @Configuration class for manual bean creation, while @Component is used for automatic component scanning.
Is @Bean singleton by default? Yes, Spring creates only one instance per container unless you specify @Scope("prototype").
Can we use @Bean without @Configuration? Yes, but not recommended — without @Configuration, Spring won’t use CGLIB proxy and may call @Bean methods multiple times.
What happens if two beans of same type exist? Spring will throw NoUniqueBeanDefinitionException unless you specify @Primary or @Qualifier.

🔹 6. Summary Table

Concept Annotation Used On Purpose Example
Configuration class @Configuration Class Tell Spring that this class defines beans @Configuration public class AppConfig { ... }
Bean definition @Bean Method Define how to create a bean @Bean public RestTemplate restTemplate() { ... }
Autowiring @Autowired Field / Constructor Inject bean from IoC container @Autowired RestTemplate restTemplate;

🔹 7. Bonus Tip: Mixing with @Component

You don’t always need @Bean.
If you own the class source code, you can directly annotate it:

@Component
public class EmailService {
    ...
}
Enter fullscreen mode Exit fullscreen mode

Spring will automatically detect it during component scan.

Use @Bean only for external classes (e.g., third-party library objects) or when you need custom construction logic.


🧭 Final Analogy Recap

Role Meaning
@Configuration Kitchen where recipes (bean methods) are written
@Bean Each recipe — defines how to make a specific dish (object)
Spring IoC The chef that reads recipes and prepares dishes (beans)
@Autowired Customer who asks the chef to serve a dish

Top comments (0)