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:
@Configuration@Configuration, Spring treats it as a configuration class, meaning it will scan for @Bean methods and process them to register beans in the application context.@Configuration class. This proxy ensures that @Bean methods are executed only once, and the same instance is returned for subsequent calls, maintaining the singleton behavior.@Configuration@Configuration (or included explicitly in the configuration).ClassPathBeanDefinitionScanner or similar mechanisms.@Configuration class and identifies all @Bean methods.@Bean method is registered as a bean definition in the Spring IoC container.@Configuration class.@Bean methods. Instead of executing the method body multiple times, it checks if the bean instance is already created and returns the existing instance if available.@Bean method and retrieves the bean instance.@Bean method and stores the result in the container.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.
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();
}
}
serviceB() would create a new ServiceB instance.