Spring Boot 中 @EnableX 注解的驱动逻辑( 三 )

readerClass = importResource.getClass("reader");for (String resource : resources) {String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);configClass.addImportedResource(resolvedResource, readerClass);}}// Process individual @Bean methodsSet beanMethods = retrieveBeanMethodMetadata(sourceClass);for (MethodMetadata methodMetadata : beanMethods) {configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));}// Process default methods on interfacesprocessInterfaces(configClass, sourceClass);// Process superclass, if anyif (sourceClass.getMetadata().hasSuperClass()) {String superclass = sourceClass.getMetadata().getSuperClassName();if (superclass != null// Superclass found, return its annotation metadata and recursereturn sourceClass.getSuperClass();}}// No superclass -> processing is completereturn null;}复制代码ConfigurationClassParser#doProcessConfigurationClass(ConfigurationClass,AnnatationMetatdata)将@PropertySource ,@ComponentScan ,@Import , @ImportResource , @Bean等一起处理了 。
看到这里基本逻辑已经理清 了 , 但是有一个疑问
@Configuration中的@Bean没有其他特殊处理吗?
浏览代码解决疑问![img](data:image/svg+xml;utf8,)
从上边浏览的代码可以看到完全模式 , 会被AOP增强
那什么是完全模式呢?在ConfigurationClassUtils找到如下方法:
public class ConfigurationClassUtils{//省略其他方法public static boolean isFullConfigurationCandidate(AnnotationMetadata metadata) {return metadata.isAnnotated(Configuration.class.getName());}}复制代码即 @Configuration class是完全模式 , @Component , @Bean是轻量级模式
那AOP增强了作用是什么呢?查看 ConfigurationClassEnhancer 的类注释如下:
/**
* Enhances {@link
Configuration
} classes by generating a CGLIB subclass which
* interacts with the Spring container to respect bean scoping semantics for
* {@code @Bean} methods. Each such {@code @Bean} method will be overridden in
* the generated subclass, only delegating to the actual {@code @Bean} method
* implementation if the container actually requests the construction of a new
* instance. Otherwise, a call to such an {@code @Bean} method serves as a
* reference back to the container, obtaining the corresponding bean by name.
* @author Chris Beams
* @author Juergen Hoeller
* @since 3.0
* @see #enhance
* @see
ConfigurationClassPostProcessor
*/
class ConfigurationClassEnhancer {
大概意思如下:
通过CGLIB增强@Configuration class 。
每个@Bean方法会生成子类 。
首次被调用时 , @Bean方法会被执行用于创建bean实例;
再次被调用时 , 不会再执行创建bean实例 , 而是根据bean名称返回首次该方法被执行时创建的bean实例 。
总结1.ConfigurationClassPostProcessor负责筛选@Component Class、@Configuration Class以及@Bean定义的Bean , **
2.ConfigurationClassParser从候选的Bean定义中解析出ConfigurationClass集合 , 随后被3.ConfigurationClassBeanDefinitionReader转换为BeanDefinition
4.ConfigurationClassParser的解析顺序 ,


推荐阅读