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.
-
Bean Creation:
- Spring scans classes annotated with annotations such as
@Component,@Service,@Repository,@Controller. - Beans can also be created through methods annotated with
@Beanin configuration classes.
- Spring scans classes annotated with annotations such as
-
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
@Configurationand are included viaspring.factories.
-
Conditional Annotations:
- Annotations like
@ConditionalOnProperty,@ConditionalOnClass,@ConditionalOnMissingBeanallow enabling or disabling configurations and beans based on conditions. - For example,
@ConditionalOnClasschecks for the presence of a specific class in the classpath, and if it exists, the bean is created.
- Annotations like
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();
}
}