spring-framework之AnnotatedBeanDefinitionReader解析

AnnotatedBeanDefinitionReader的作用

Spring源码中类的命名还是很讲究的,AnnotatedBeanDefinitionReader它的作用如同它本身的命名,主要是为了解析带有注解的bean的beanDefinition,并将其注册到Bean工厂中。在此类的注释中也有介绍,功能与ClassPathBeanDefinitionScanner类似,但是不同的是AnnotatedBeanDefinitionReader是必需要去指定某个class或class数组。下面来介绍此类的主要属性和方法,以及核心方法的执行流程。

属性和构造器

属性

	private final BeanDefinitionRegistry registry;

	private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();

	private ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();

	private ConditionEvaluator conditionEvaluator;
  • BeanDefinitionRegistry 是bean定义的一个注册器。一般也就是ApplicationContext本身,或者说是BeanFactory本身也可以。他们都是BeanDefinitionRegistry的子类。主要作用就是对beanDefinition的增删查等操作,当然查出来之后也是可以修改beanDefinition的。
  • BeanNameGenerator 是bean名称的生成器。其实现类AnnotationBeanNameGenerator主要就是解析带有注解的beanDefinition,因为@Component注解的value默认就是其beanName,当然Spring也支持@ManagedBean和@Named注解,一般我们不指定,那AnnotationBeanNameGenerator就会从beanDefinition中获取beanClassName,也就是class的全路径名,截取其最后的Class名,然后首字母小写;另外如果beanClass是IUserService这种形式,那么beanClassName就是IUserService。
  • ScopeMetadataResolver 是bean的一个作用域解析器,主要作用就是解析bean上的@Scope注解,一般不指定也就是默认singleton单例。当然也可以指定为prototype。Spring就会在每次获取该bean的时候,重新构造一个对象。但要注意有单例bean引用原型bean的情况,原型bean会失效。
  • ConditionEvaluator 是主要是作为条件判断用。如果此bean上有@Conditional注解,Spring此类中解析bean定义时,判断是否需要跳过此bean。如果不满足条件,就不会注册此bean。此注解在SpringBoot中大放光彩,是实现自动配置的核心之一。

构造器

	/**
	 * Create a new {@code AnnotatedBeanDefinitionReader} for the given registry.
	 * If the registry is {@link EnvironmentCapable}, e.g. is an {@code ApplicationContext},
	 * the {@link Environment} will be inherited, otherwise a new
	 * {@link StandardEnvironment} will be created and used.
	 * @param registry the {@code BeanFactory} to load bean definitions into,
	 * in the form of a {@code BeanDefinitionRegistry}
	 * @see #AnnotatedBeanDefinitionReader(BeanDefinitionRegistry, Environment)
	 * @see #setEnvironment(Environment)
	 */
	public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
		this(registry, getOrCreateEnvironment(registry));
	}

	/**
	 * Create a new {@code AnnotatedBeanDefinitionReader} for the given registry and using
	 * the given {@link Environment}.
	 * @param registry the {@code BeanFactory} to load bean definitions into,
	 * in the form of a {@code BeanDefinitionRegistry}
	 * @param environment the {@code Environment} to use when evaluating bean definition
	 * profiles.
	 * @since 3.1
	 */
	public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		Assert.notNull(environment, "Environment must not be null");
		this.registry = registry;
		this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
		AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
	}

通过此出两个构造器,我们可以知道此bean定义读取器是必需要传入一个BeanDefinitionRegistry来注册bean定义。这无可厚非,我们主要关心的是其中一行代码。

	AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);

其主要作用就是一个预处理,为传入的BeanDefinitionRegistry提前注册一些和解析注解相关的后置处理器。我们点进去看一看究竟。

	/**
	 * Register all relevant annotation post processors in the given registry.
	 * @param registry the registry to operate on
	 * @param source the configuration source element (already extracted)
	 * that this registration was triggered from. May be {@code null}.
	 * @return a Set of BeanDefinitionHolders, containing all bean definitions
	 * that have actually been registered by this call
	 */
	public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, @Nullable Object source) {

		// 获取原生的,未包装的beanFactory
		DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
		if (beanFactory != null) {
			// 注册一个解析@Order的比较器
			if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
				beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
			}
			// 可以解析@Lazy注解,延迟处理的解析器,其父类也可以解析@Qualifier注解
			if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
				beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
			}
		}

		Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);

		// 注册一个ConfigurationClassPostProcessor后置处理器,非常重要的一个Spring内部类
		// 后续可通过已经注册的BeanDefinition来扫描解析其它bean。
		if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// 注册一个可以解析@Autowired注解的后置处理器
		// 后期在bean实例化后,初始化bean时依赖注入的核心类
		if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// 注册一个可以解析@Required注解的后置处理器
		if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// 注册一个可以解析@Resource注解的后置处理器
		// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
		if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// 处理JPA相关业务,没有不会注册此处理器
		// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
		if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition();
			try {
				def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
						AnnotationConfigUtils.class.getClassLoader()));
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
			}
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// 注册一个解析@EventListener注解的后置处理器,用于转换为ApplicationListener.事件监听作用。
		if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
		}

		// 注册监听器工厂类,可以创造ApplicationListenerMethodAdapter,此类实现于ApplicationListener。
		// 此类主要配合上边的EventListenerMethodProcessor使用
		if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
		}

		return beanDefs;
	}

代码看着挺多的,其实都是使用BeanDefinitionRegistry去注册一些bean定义,这些bean定义都是Spring的内部类,主要是为了在后期初始化或实例化bean时,去解析处理bean的。当然这些被注册的bean定义都是非常重要的类,后续解析bean定义,以及实例化和初始化bean时会起作用。

核心方法

此类中的主要核心方法也就是register和registerBean方法了,跟着代码一路走下去。也就走到了doRegisterBean这个实际起作用的方法中。

/**
 * Register a bean from the given bean class, deriving its metadata from
 * class-declared annotations.
 * @param annotatedClass the class of the bean
 * @param instanceSupplier a callback for creating an instance of the bean
 * (may be {@code null})
 * @param name an explicit name for the bean
 * @param qualifiers specific qualifier annotations to consider, if any,
 * in addition to qualifiers at the bean class level
 * @param definitionCustomizers one or more callbacks for customizing the
 * factory's {@link BeanDefinition}, e.g. setting a lazy-init or primary flag
 * @since 5.0
 */
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
		@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {

	// 解析带有注解的bean,需要此种BeanDefinition来解析
	AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);

	// 解析@Conditional注解,判断是否需要跳过此bean的注册
	if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
		return;
	}

	// 提供一个回调函数给此bean,后期在实例化此bean时会调用回调方法,来提供一个bean实例。
	// 相当于自定义bean的实例化,不使用Spring的实例化策略。
	abd.setInstanceSupplier(instanceSupplier);
	// 解析@Scope注解,默认单例
	ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
	abd.setScope(scopeMetadata.getScopeName());
	// 调用beanNameGenerator给此bean生成一个beanName,或者说beanId,必需是唯一的。
	String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));

	// 处理一些通用注解@Lazy,@@Primary,@DependsOn,@Role和@Description
	AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
	// 此处主要是通过传入的注解来给构造此beanDefinitionn,一般不需要特殊传入注解,默认为null。
	if (qualifiers != null) {
		for (Class<? extends Annotation> qualifier : qualifiers) {
			if (Primary.class == qualifier) {
				abd.setPrimary(true);
			}
			else if (Lazy.class == qualifier) {
				abd.setLazyInit(true);
			}
			else {
				abd.addQualifier(new AutowireCandidateQualifier(qualifier));
			}
		}
	}
	// 给我们一个自定义BeanDefinition的机会,不过一般不需要,走Spring正常的流程即可。
	for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
		customizer.customize(abd);
	}
	// 注册BeanDefinition到beanFatory
	BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
	// 解析@Scope的代理模式,一般应用在作用域是session或request。
	definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
	BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
	}

此方法就是解析并注册一个beanDefinition的流程,主要就是针对bean上的各种注解进行解析,当然这些也是此bean的元信息。流程写在了代码中,不在过多说明,流程并不难理解,此方法的调用处也是循环每一个class类执行此方法的。

总结

AnnotatedBeanDefinitionReader此类的基本作用就是解析class为BeanDefinition,然后注册到BeanFactory中,当然构造器中也向BeanFactory中提前注册了一些内部后置处理器类用于之后的bean解析及实例化等操作。暂时就这些把,后续有新的体会或补充,再继续更新此帖子。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值