转载

Spring源码分析

首先我们采用Spring官方推荐的JavaConfig风格+注解的方式来初始化Spring:

// 配置类
@Configuration
@ComponentScan(basePackages = {"com.demo.learn.service"})
public class AppConfig {
}

// 入口类
public static void main(String[] args) {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
    DemoServiceImpl serviceImpl =  (DemoServiceImpl)applicationContext.getBean(DemoServiceImpl.class);
    System.out.println(serviceImpl);
}
复制代码

1.1 进入AnnotationConfigApplicationContext的构造方法

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
    // 调用自身无参构造方法 -> 1.2
	this();
	register(annotatedClasses);
	refresh();
}
复制代码

1.2 点击this()进入无参构造方法,

AnnotationConfigApplicationContext继承了GenericApplicationContext所以此处隐式调用了父类的无参构造方法创建了一个Bean工厂:DefaultListableBeanFactory

GenericApplicationContext 实现了 BeanDefinitionRegistry 接口,而 AnnotationConfigApplicationContext 继承了 GenericApplicationContext ,所以 AnnotationConfigApplicationContext 就是一个registry

BeanDefinitionRegistry 是一个接口,定义了关于 BeanDefinition 的注册、移除、查询等一系列的操作。该接口有三个实现类:DefaultListableBeanFactory、GenericApplicationContext、SimpleBeanDefinitionRegistry,其中 GenericApplicationContext 底层调用的是 DefaultListableBeanFactory 中的实现方法,所以严格意义上来说,只有两个实现类。

public GenericApplicationContext() {
	this.beanFactory = new DefaultListableBeanFactory();
}
复制代码

此处初始化了一个读取器和一个扫描器

// 注解形式bean的读取器
private final AnnotatedBeanDefinitionReader reader;

// ... 
public AnnotationConfigApplicationContext() {
    // 给注册表创建一个bean读取器
    // 初始化一个DefaultListableBeanFactory -> 1.3
	this.reader = new AnnotatedBeanDefinitionReader(this);
	//scanner的用处不是很大,它仅仅是在我们外部手动调用 .scan 等方法才有用,常规方式是不会用到scanner对象的
	this.scanner = new ClassPathBeanDefinitionScanner(this);
}
复制代码

1.3 进入 this.reader = new AnnotatedBeanDefinitionReader(this); 一路点下去,我们会看到一系列初始化过程

public ConditionContextImpl(@Nullable BeanDefinitionRegistry registry,
		@Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {

	this.registry = registry;
	this.beanFactory = deduceBeanFactory(registry);
	this.environment = (environment != null ? environment : deduceEnvironment(registry));
	this.resourceLoader = (resourceLoader != null ? resourceLoader : deduceResourceLoader(registry));
	this.classLoader = deduceClassLoader(resourceLoader, this.beanFactory);
}
复制代码

1.4 初始化DefaultListableBeanFactory并注册各种Processor

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
		BeanDefinitionRegistry registry, @Nullable Object source) {
    // 创建beanFactory
	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<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);

	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));
	}
    // ...
}
复制代码

BeanDefinition是什么,顾名思义,它是用来描述Bean的,里面存放着关于Bean的一系列信息,比如Bean的作用域,Bean所对应的Class,是否懒加载,是否Primary等等,这个BeanDefinition也相当重要

1.5 进入 DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);

在此之前registry为 AnnotationConfigApplicationContext ,根据1.2得知是 GenericApplicationContext 的子类,执行1.5.1处代码

@Nullable
private static DefaultListableBeanFactory unwrapDefaultListableBeanFactory(BeanDefinitionRegistry registry) {
	if (registry instanceof DefaultListableBeanFactory) {
		return (DefaultListableBeanFactory) registry;
	}
	// 1.5.1
	else if (registry instanceof GenericApplicationContext) {
		return ((GenericApplicationContext) registry).getDefaultListableBeanFactory();
	}
	else {
		return null;
	}
}
复制代码

1.5.2 进入1.5.1代码块,可以看到,返回的是 GenericApplicationContextbeanFactorybeanFactory 在1.2的时候已经被赋值为 DefaultListableBeanFactory

public final DefaultListableBeanFactory getDefaultListableBeanFactory() {
	return this.beanFactory;
}
复制代码

1.6 上面方法中有一个 registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME) 方法,我们点进去可以看到这个方法中给 RootBeanDefinition 设置了一个角色 BeanDefinition.ROLE_INFRASTRUCTURE , 此角色表名用此方法注册的bean完全是spring的内部bean,与最终用户无关

1.6.1 角色

  • 0: 用户自定义的Bean
  • 1:来源于配置文件的Bean
  • 2:Spring内部的Bean
private static BeanDefinitionHolder registerPostProcessor(
		BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {

	definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
	registry.registerBeanDefinition(beanName, definition);
	return new BeanDefinitionHolder(definition, beanName);
}
复制代码

1.7 点击进入 registry.registerBeanDefinition(beanName, definition) 方法

可以看到这个方法是一个接口,先来看下此接口都有哪些方法

public interface BeanDefinitionRegistry extends AliasRegistry {
    // 注册BeanDefinition
    void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException;
    // 移除BeanDefinition
    void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
    // 获取BeanDefinition
    BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
    // 根据bean name判断是否存在BeanDefinition
    boolean containsBeanDefinition(String beanName);
    // 获取所有的BeanDefinition
    String[] getBeanDefinitionNames();
    // 获取BeanDefinition数量
    int getBeanDefinitionCount();
    // 判断bean name是否被占用
    boolean isBeanNameInUse(String beanName);
}
复制代码

此时我们需要找它的实现类(由1.5.2得知为DefaultListableBeanFactory)

这个类就是我们的Bean容器所在的位置

private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {

    // 存储所有的BeanDefinition,key就是bean name,这个Map就是我们一直所说的Bean容器
    private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
    // 存储所有的bean name
    private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
    
    /**
     * 注册bean
     * @param beanName          bean name
     * @param BeanDefinition    bean对应的BeanDefinition
     */
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
    		throws BeanDefinitionStoreException {
    
    	Assert.hasText(beanName, "Bean name must not be empty");
    	Assert.notNull(beanDefinition, "BeanDefinition must not be null");
    
    	if (beanDefinition instanceof AbstractBeanDefinition) {
    		try {
    		     // 验证:
    		        1. 验证是否重写了方法
    		        2. 如果重写了方法,通过beanName获取方法,如果为0则方法不存在,抛出异常,为1则设置overload属性为false
    			((AbstractBeanDefinition) beanDefinition).validate();
    		}
    		catch (BeanDefinitionValidationException ex) {
    			throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
    					"Validation of bean definition failed", ex);
    		}
    	}
    
        // 从bean容器(beanDefinitionMap)中通过beanName获取beanDefinition
    	BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
    	if (existingDefinition != null) {
    	    // 判断是否允许重写beanDefinition,不允许则抛出异常
    		if (!isAllowBeanDefinitionOverriding()) {
    			throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
    		}
    		// 当原beanDefinition的角色小于新的beanDefinition角色时,输出warn日志,提示beanDefinition被覆盖
    		else if (existingDefinition.getRole() < beanDefinition.getRole()) {
    			// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
    			if (logger.isInfoEnabled()) {
    				logger.info("Overriding user-defined bean definition for bean '" + beanName +
    						"' with a framework-generated bean definition: replacing [" +
    						existingDefinition + "] with [" + beanDefinition + "]");
    			}
    		}
    		// 当新beanDefinition的属性值不等于原beanDefinition的属性值时,输出info提示beanDefinition被覆盖
    		else if (!beanDefinition.equals(existingDefinition)) {
    			if (logger.isDebugEnabled()) {
    				logger.debug("Overriding bean definition for bean '" + beanName +
    						"' with a different definition: replacing [" + existingDefinition +
    						"] with [" + beanDefinition + "]");
    			}
    		}
    		else {
    			if (logger.isTraceEnabled()) {
    				logger.trace("Overriding bean definition for bean '" + beanName +
    						"' with an equivalent definition: replacing [" + existingDefinition +
    						"] with [" + beanDefinition + "]");
    			}
    		}
    		// 添加至bean容器,并覆盖原beanDefinition
    		this.beanDefinitionMap.put(beanName, beanDefinition);
    	} 
    	// 容器中无对应的beanDefinition则直接注册
    	else {
    	    // 判断此工厂bean创建流程是否已经开始
    		if (hasBeanCreationStarted()) {
    			// Cannot modify startup-time collection elements anymore (for stable iteration)
    			synchronized (this.beanDefinitionMap) {
    			    // 添加beanDefinition至bean容器
    				this.beanDefinitionMap.put(beanName, beanDefinition);
    				// 创建新的beanNames集合,并将已经存在的beanNames放入该集合
    				List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
    				updatedDefinitions.addAll(this.beanDefinitionNames);
    				updatedDefinitions.add(beanName);
    				this.beanDefinitionNames = updatedDefinitions;
    				// 在手动创建bean的集合中,如果存在同名的beanName,则将集合中已经存的beanName移除
    				if (this.manualSingletonNames.contains(beanName)) {
    					Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
    					updatedSingletons.remove(beanName);
    					this.manualSingletonNames = updatedSingletons;
    				}
    			}
    		}
    		else {
    			// Still in startup registration phase
    			// 将当前bean对应的beanDefinition放入容器中
    			this.beanDefinitionMap.put(beanName, beanDefinition);
    			// 将当前beanName放入beanDefinitionNames中
    			this.beanDefinitionNames.add(beanName);
    			// 删除同名的beanName
    			this.manualSingletonNames.remove(beanName);
    		}
    		// 将保存冻结beanDefinition的Map设为null
    		this.frozenBeanDefinitionNames = null;
    	}
    
        // 如果当前注册的beanDefinition已经存在,或者在(缓存单例bean实例map)中存在
    	if (existingDefinition != null || containsSingleton(beanName)) {
    	    // 重置给定bean的所有bean定义缓存,包括从其派生的bean的缓存
    		resetBeanDefinition(beanName);
    	}
    }
}
复制代码

参考 juejin.im/post/5c637d…

原文  https://juejin.im/post/5f01a83d6fb9a07e654f95cb
正文到此结束
Loading...