【Spring注解系列05】@Import注入原理

1.@Import注解

  • 用于注入指定的类,导入组件id默认是组件的全类名。
  • 只能作用于类上。
  • 属性:value = {xx.class,xx.class}        说明:xx.class为要导入到容器中的组件

属性value中class分为三类:

     1)普通类直接注入

     2)实现ImportSelector接口的类

     3)实现ImportBeanDefinitionRegistrar接口的类

说明:

  • ImportSelector:返回需要导入的组件的全类名数组
  • ImportBeanDefinitionRegistrar:手动注册bean到容器中;

 

2.@Import注入原理

import类注入是通过org.springframework.context.annotation.ConfigurationClassPostProcessor后置处理器来注入的。

核心方法:postProcessBeanDefinitionRegistry

     /**
	 * Derive further bean definitions from the configuration classes in the registry.
	 */
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
		int registryId = System.identityHashCode(registry);

        //判断后置处理器在registriesPostProcessed和factoriesPostProcessed中有没有被调用过
		if (this.registriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
		}
		if (this.factoriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanFactory already called on this post-processor against " + registry);
		}

        //调用前保存registryId,防止被重复调用
		this.registriesPostProcessed.add(registryId);

        //注入标有@configuration的对象
		processConfigBeanDefinitions(registry);
	}



    /**  构建和校验标有@configuration注解的对象
	 * Build and validate a configuration model based on the registry of
	 * {@link Configuration} classes.   
	 */
	public void processConfigBeanDefinitions(BeanDefinitionRegistry re
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值