Sobes.tech
Senior

How does Spring build the process of creating beans from the moment the application starts? How do auto-configurations and conditional annotations work?

sobes.tech AI

Answer from AI

The Spring Framework creates an application context (ApplicationContext) when starting an application, which manages the creation and lifecycle of beans.

  1. Bean Creation:

    • Spring scans classes annotated with annotations such as @Component, @Service, @Repository, @Controller.
    • Beans can also be created through methods annotated with @Bean in configuration classes.
  2. Auto-configuration:

    • Spring Boot uses an auto-configuration mechanism that automatically configures beans based on dependencies in the classpath and settings.
    • Auto-configuration classes are annotated with @Configuration and are included via spring.factories.
  3. Conditional Annotations:

    • Annotations like @ConditionalOnProperty, @ConditionalOnClass, @ConditionalOnMissingBean allow enabling or disabling configurations and beans based on conditions.
    • For example, @ConditionalOnClass checks for the presence of a specific class in the classpath, and if it exists, the bean is created.

Thus, Spring dynamically manages bean creation, considering configurations, dependencies, and conditions, allowing flexible application setup without manual intervention.

Example of conditional auto-configuration:

@Configuration
@ConditionalOnClass(DataSource.class)
public class DataSourceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public DataSource dataSource() {
        // Create DataSource if absent
        return new HikariDataSource();
    }
}