DEV Community

gaurbprajapati
gaurbprajapati

Posted on

Understanding @Configuration in Spring Boot

🔹 What is @Configuration?

@Configuration is a class-level annotation in Spring Framework that tells the Spring IoC container
that the class contains one or more bean definitions.

It is part of the Spring Core module and is used to define beans in Java code instead of XML.

In short:

@Configuration marks a class as a configuration class, where Spring will look for methods annotated with @Bean to register them as beans inside the ApplicationContext.


🧠 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

In this example:

  • The AppConfig class is annotated with @Configuration.
  • It declares two beans: Database and UserService.
  • Spring will scan this class at startup, execute the @Bean methods, and register those objects inside the IoC container.

🔹 When is @Configuration Used?

You use @Configuration when:

  1. ✅ You want to define multiple beans in one class.
    Example: You have multiple related services, helpers, or configuration objects.

  2. ✅ You need to configure third-party or external classes that can’t be annotated with @Component.
    Example: Configuring RestTemplate, ObjectMapper, or custom data sources.

  3. ✅ You want to group related beans together logically.
    Example: DatabaseConfig, SecurityConfig, MailConfig, etc.

  4. ✅ You need fine control over bean creation, including parameters, environment variables, or custom initialization.

  5. ✅ You want Spring to manage your @Bean methods correctly — ensuring each is a singleton even if one bean calls another.


🧩 Example Use Cases:

Example 1: Configuring Third-Party Beans

@Configuration
public class RestTemplateConfig {

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

Here, you can’t annotate RestTemplate with @Component (it’s part of Spring library code),
so you use a configuration class to define it manually.


Example 2: Grouping Related Beans

@Configuration
public class DataConfig {

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

    @Bean
    public DataSource dataSource(Database database) {
        return new DataSource(database);
    }
}
Enter fullscreen mode Exit fullscreen mode

Both Database and DataSource are part of the same configuration,
so grouping them inside one @Configuration class makes the design clean and modular.


🔹 Why is @Configuration Used?

There are several reasons why @Configuration is important and preferred over plain @Bean usage.

Reason Explanation
🧱 Java-based configuration It replaces old XML-based configuration. You can define beans directly in Java.
⚙️ Full control over bean creation You can specify constructors, parameters, and conditional logic during bean creation.
🔁 Ensures singleton beans When one @Bean method calls another, Spring returns the same managed bean (not a new instance).
🧩 Organizes your app configuration You can create separate configuration classes for different modules (DB, Security, Email, etc.).
🚀 Integrates with Spring Boot auto-configuration You can combine your custom configuration with Spring Boot’s built-in auto-config.

⚠️ What Happens Without @Configuration?

If you remove @Configuration and keep only @Bean annotations:

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

    @Bean
    public UserService userService() {
        return new UserService(database()); // will create a new instance!
    }
}
Enter fullscreen mode Exit fullscreen mode

Then Spring won’t use CGLIB proxying, meaning:

  • Each time you call database(), it creates a new Database object.
  • Beans won’t be singletons anymore.
  • You may get unexpected behavior or duplicate objects.

That’s why @Configuration is important — it ensures singleton behavior of beans.


🔹 Internal Working (Behind the Scenes)

Here’s what happens internally when you use @Configuration:

  1. Spring Boot starts the application.
  2. It scans the classpath for @Configuration classes.
  3. Each @Configuration class is enhanced (proxied) using CGLIB.
  4. When a @Bean method is called, Spring checks:
  • “Do I already have this bean in my container?”
  • If yes → Return existing bean.
  • If no → Create it, store it, and return it.
    1. The IoC container now holds all defined beans, ready for dependency injection.

🔄 Simplified Flow Diagram

+-------------------------------------+
|   Spring Boot Application Starts    |
+------------------+------------------+
                   |
                   v
        [Component Scanning Starts]
                   |
                   v
    +---------------------------------+
    |  Finds @Configuration Classes   |
    +---------------------------------+
                   |
                   v
       Create CGLIB Proxy for Class
                   |
                   v
        Call Each @Bean Method Once
                   |
                   v
      Register Returned Object as Bean
                   |
                   v
     Beans Available in IoC Container
                   |
                   v
     Other Classes Can @Autowired Them
Enter fullscreen mode Exit fullscreen mode

🔹 Summary

Concept Description
Annotation @Configuration
Type Class-level
Purpose Marks the class as a source of bean definitions
Works With @Bean methods
Ensures Beans are singletons, managed by Spring IoC
Use Case When defining multiple or custom beans programmatically

🧭 Final Takeaway

✅ Use @Configuration when you want to declare one or more beans inside a class and let Spring manage them as singletons in the IoC container.

It gives you cleaner, modular, and more controlled configuration, replacing the old XML style with elegant Java code.

Top comments (0)