栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring源码解析(3)之容器前期准备

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring源码解析(3)之容器前期准备

        写了BeanFactoryPostProcessor的博客才发现,需要提前先介绍spring在解析之前做的容器准备,要不然感觉直接介绍解析源码的话,会有一点懵逼,这里会介绍Spring容器前期准备。

        这里问题问题:AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);这句代码相信很多人都用过并且很熟悉,但是大家有思考过,它为了我们做了哪些事情?

        一AnnotationConfigApplicationContext的构造函数         i1:org.springframework.context.annotation.AnnotationConfigApplicationContext#AnnotationConfigApplicationContext
	public AnnotationConfigApplicationContext(Class... annotatedClasses) {
		// 调用无参的构造器,会调用父类的无参构造器
        this();
        // 注册配合类
		register(annotatedClasses);
        // 容器刷新
		refresh();
	}
       i2>org.springframework.context.support.GenericApplicationContext#GenericApplicationContext()

        然后我们看下父类的构造函数,调用父类的构造函数,创建一个IOC容器。

	
	public GenericApplicationContext() {
		this.beanFactory = new DefaultListableBeanFactory();
	}
       i3>org.springframework.context.annotation.AnnotationConfigApplicationContext#AnnotationConfigApplicationContext()

        然后调用自己的构造方法:

	
	public AnnotationConfigApplicationContext() {
        // 为IOC容器赋值,AnnotatedBeanDefinitionReader(注解bean定义的读取器)
		this.reader = new AnnotatedBeanDefinitionReader(this);
        // 为IOC容器赋值 类路径下的bean定义扫描器
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}
         i3.1>org.springframework.context.annotation.AnnotatedBeanDefinitionReader#AnnotatedBeanDefinitionReader        

        org.springframework.context.annotation.AnnotatedBeanDefinitionReader#AnnotatedBeanDefinitionReader 为bean定义读取器赋值

	
	public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
		this(registry, getOrCreateEnvironment(registry));
	}

        i3.1.1>org.springframework.context.annotation.AnnotatedBeanDefinitionReader#getOrCreateEnvironment        

        org.springframework.context.annotation.AnnotatedBeanDefinitionReader#getOrCreateEnvironment 创建环境

	
	private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		if (registry instanceof EnvironmentCapable) {
			return ((EnvironmentCapable) registry).getEnvironment();
		}
		return new StandardEnvironment();
	}

         i3.2>org.springframework.context.annotation.Conditionevaluator 创建一个条件计算器对象

	
	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);
	}

        条件计算器对象。

		public ConditionContextImpl(BeanDefinitionRegistry registry, Environment environment, ResourceLoader resourceLoader) {
			this.registry = registry;
			this.beanFactory = deduceBeanFactory(registry);
			this.environment = (environment != null ? environment : deduceEnvironment(registry));
			this.resourceLoader = (resourceLoader != null ? resourceLoader : deduceResourceLoader(registry));
		}

          i3.3> AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);为容器注册系统的bean定义信息

  1. 首先获取一个IOC容器
  2. 注册一个配置类解析器的bean定义ConfigurationClassPostProcessor
  3. 设置@AutoWired注解解析器的bean定义
  4. 设置@Required注解处理器
  5. 检查是否支持JSR250规范,如果支持则注册解析JSR250规范的注解
  6. 检查是否支持jpa,若支持则注册jpa规范的注解
  7. 注册解析@EventListener的注解
public static Set registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, Object source) {
		
		// 获取一个IOC容器
		DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
		if (beanFactory != null) {
			if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
				beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
			}
			if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
				beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
			}
		}

		Set beanDefs = new linkedHashSet(8);
		
		// 注册一个配置类解析器的bean定义ConfigurationClassPostProcessor
		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定义信息
		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));
		}

		// 检查是否支持JSR250规范,如果支持则注册JSR250规范的注解
		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,若支持注册解析jpa注解的规范
		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的注解
		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));
		}

		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;
	}

        i4>:    this.scanner = new ClassPathBeanDefinitionScanner(this);创建类路径下的bean定义扫描器

	
	public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
			Environment environment, ResourceLoader resourceLoader) {

		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		this.registry = registry;
          
        // 使用默认的规则
		if (useDefaultFilters) {
			registerDefaultFilters();
		}
        // 设置环境
		setEnvironment(environment);
        // 设置资源加载器
		setResourceLoader(resourceLoader);
	}

          i4.1>: org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#registerDefaultFilters注册包扫描默认的规则 

	
	@SuppressWarnings("unchecked")
	protected void registerDefaultFilters() {
		this.includeFilters.add(new AnnotationTypeFilter(Component.class));
		ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
		try {
			this.includeFilters.add(new AnnotationTypeFilter(
					((Class) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));
			logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
		}
		catch (ClassNotFoundException ex) {
			// JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.
		}
		try {
			this.includeFilters.add(new AnnotationTypeFilter(
					((Class) ClassUtils.forName("javax.inject.Named", cl)), false));
			logger.debug("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");
		}
		catch (ClassNotFoundException ex) {
			// JSR-330 API not available - simply skip.
		}
	}

        i5>org.springframework.context.annotation.AnnotatedBeanDefinitionReader#register 使用

        i3.1步生成的bean定义读取器注册配置类

        

	public void registerBean(Class annotatedClass, String name, Class... qualifiers) {
		AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
		if (this.conditionevaluator.shouldSkip(abd.getmetadata())) {
			return;
		}

		Scopemetadata scopemetadata = this.scopemetadataResolver.resolveScopemetadata(abd);
		abd.setScope(scopemetadata.getScopeName());
		String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
		AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
		if (qualifiers != null) {
			for (Class qualifier : qualifiers) {
				if (Primary.class == qualifier) {
					abd.setPrimary(true);
				}
				else if (Lazy.class == qualifier) {
					abd.setLazyInit(true);
				}
				else {
					abd.addQualifier(new AutowireCandidateQualifier(qualifier));
				}
			}
		}
        
        // 注册自己传入的主配置类bean定义到容器中
		BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
		definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopemetadata, definitionHolder, this.registry);
		BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
	}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/314514.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号