The @Configuration annotation in Spring Framework is used to indicate that a class declares one or more @Bean methods and serves as a source of bean definitions for the Spring IoC (Inversion of Control) container. It plays a crucial role in Spring's Java-based configuration.

Here’s a detailed explanation of how @Configuration works internally:


Key Roles of @Configuration

  1. Marks a Class as a Configuration Class:
  2. Enhances the Class with CGLIB Proxy:

Internal Workflow of @Configuration

  1. Class Scanning:
  2. Bean Definition Parsing:
  3. CGLIB Proxy Creation:
  4. Bean Creation and Dependency Injection:

Why CGLIB Proxy is Needed?

Without the CGLIB proxy, calling an @Bean method from within another @Bean method would create a new instance of the bean every time, breaking the singleton contract.

Example Without Proxy:

java
Copy code
@Configuration
public class AppConfig {
    @Bean
    public ServiceA serviceA() {
        return new ServiceA(serviceB()); // Calls serviceB() directly
    }

    @Bean
    public ServiceB serviceB() {
        return new ServiceB();
    }
}

Example With Proxy: