Record how spring realizes yml automatic assembly when looking at the spring boot source code.
In the spring boot startup class, it
@SpringBootApplicationis the clue
@EnableAutoConfigurationto realize automatic assembly, and the core of automatic assembly can be found through the code .
EnableAutoConfigurationFind it in the class and
continue to follow the code. The method of getCandidateConfigurations in the selectImports method to obtain the auto-assembly class is to find the META-INF/spring.factories file in the spring-boot-autoconfigure package META-INF/spring through the class loader. The configuration of factories automatic assembly class takes our commonly used redis as an example, let's see how spring completes the automatic assembly.
- @ConditionalOnProperty: If there is a specified configuration, the condition takes effect;
- @ConditionalOnBean: If there is a specified Bean, the condition takes effect;
- @ConditionalOnClass: When there is a specified class in the class path, the condition takes effect;
- @ConditionalOnMissingBean: If there is no specified bean, the condition takes effect;
- @ConditionalOnMissingClass: If there is no specified Class, the condition takes effect;
- @ConditionalOnWebApplication: Conditions take effect in the Web environment;
- @ConditionalOnExpression: Determine whether the condition is valid according to the expression.
Therefore, only by adding spring-boot-starter-data-redis to the pom.xml file, the automatic configuration of redis will take effect, and we can see the regular configuration injection.
@EnableConfigurationPropertiesRedisProperties.class configured in
Spring Boot finds all the automatic configuration classes in the META-INF/spring.factories configuration file under the project jar package through the @EnableAutoConfiguration annotation, loads them according to the conditions, and reads the configuration information from the configuration file through the @ConfigurationProperties annotation, and Inject it into it to complete the assembly.