Spring注解驱动开发——AOP原理源码解析

AOP的底层原理:

1、创建AnnotationAwareAspectJAutoProxyCreator

在容器启动时会注册配置类,并调用refresh()方法,创建容器中的所有bean并装配bean的属性和功能等

public AnnotationConfigApplicationContext(Class... annotatedClasses) {
	this();
	register(annotatedClasses);
	refresh();
}

容器刷新做的操作: 

public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// Prepare this context for refreshing.
		prepareRefresh();

		// Tell the subclass to refresh the internal bean factory.
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// Prepare the bean factory for use in this context.
		prepareBeanFactory(beanFactory);

		try {
			// Allows post-processing of the bean factory in context subclasses.
			postProcessBeanFactory(beanFactory);

			// Invoke factory processors registered as beans in the context.
			invokeBeanFactoryPostProcessors(beanFactory);

			// Register bean processors that intercept bean creation.
			registerBeanPostProcessors(beanFactory);

			// Initialize message source for this context.
			initMessageSource();

			// Initialize event multicaster for this context.
			initApplicationEventMulticaster();

			// Initialize other special beans in specific context subclasses.
			onRefresh();

			// Check for listener beans and register them.
			registerListeners();

			// Instantiate all remaining (non-lazy-init) singletons.
			finishBeanFactoryInitialization(beanFactory);

			// Last step: publish corresponding event.
			finishRefresh();
		}

		catch (BeansException ex) {
			if (logger.isWarnEnabled()) {
				logger.warn("Exception encountered during context initialization - " +
						"cancelling refresh attempt: " + ex);
			}

			// Destroy already created singletons to avoid dangling resources.
			destroyBeans();

			// Reset 'active' flag.
			cancelRefresh(ex);

			// Propagate exception to caller.
			throw ex;
		}

		finally {
			// Reset common introspection caches in Spring's core, since we
			// might not ever need metadata for singleton beans anymore...
			resetCommonCaches();
		}
	}
}

有一处是注册bean的后置处理器(registerBeanPostProcessors(beanFactory);包括自定义的后置处理器和Spring自带的后置处理器),用来拦截bean的创建:

public static void registerBeanPostProcessors(
		ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

	String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

	// Register BeanPostProcessorChecker that logs an info message when
	// a bean is created during BeanPostProcessor instantiation, i.e. when
	// a bean is not eligible for getting processed by all BeanPostProcessors.
	int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

	// Separate between BeanPostProcessors that implement PriorityOrdered,
	// Ordered, and the rest.
	List priorityOrderedPostProcessors = new ArrayList<>();
	List internalPostProcessors = new ArrayList<>();
	List orderedPostProcessorNames = new ArrayList<>();
	List nonOrderedPostProcessorNames = new ArrayList<>();
	for (String ppName : postProcessorNames) {
		if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			priorityOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			orderedPostProcessorNames.add(ppName);
		}
		else {
			nonOrderedPostProcessorNames.add(ppName);
		}
	}

	// First, register the BeanPostProcessors that implement PriorityOrdered.
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

	// Next, register the BeanPostProcessors that implement Ordered.
	List orderedPostProcessors = new ArrayList<>();
	for (String ppName : orderedPostProcessorNames) {
		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
		orderedPostProcessors.add(pp);
		if (pp instanceof MergedBeanDefinitionPostProcessor) {
			internalPostProcessors.add(pp);
		}
	}
	sortPostProcessors(orderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, orderedPostProcessors);

	// Now, register all regular BeanPostProcessors.
	List nonOrderedPostProcessors = new ArrayList<>();
	for (String ppName : nonOrderedPostProcessorNames) {
		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
		nonOrderedPostProcessors.add(pp);
		if (pp instanceof MergedBeanDefinitionPostProcessor) {
			internalPostProcessors.add(pp);
		}
	}
	registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

	// Finally, re-register all internal BeanPostProcessors.
	sortPostProcessors(internalPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, internalPostProcessors);

	// Re-register post-processor for detecting inner beans as ApplicationListeners,
	// moving it to the end of the processor chain (for picking up proxies etc).
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

该方法首先会获取到配置类中所有bean的后置处理器

给容器添加别的后置处理器类

优先注册实现了PriorityOrdered接口的BeanPostProcessor

再注册实现了Ordered接口的BeanPostProcessor

注册没实现优先级接口(Ordered)的BeanPostProcessor

注册BeanPostProcessor实际上就是有则从BeanFactory中获取,没有则创建BeanPostProcessor对象,并将其置于容器中,步骤:

    1、创建bean实例

    2、populateBean():给bean的各种属性赋值

    3、initializeBean():初始化bean,bean的后置处理器就是在该方法的前后工作的,初始化时:

        ①调用invokeAwareMethods,处理Aware接口的方法回调

        ②调用applyBeanPostProcessorBeforeInitialization()方法,运行所有后置处理器的postProcessBeforeInitialization前置方法

        ③调用invokeInitMethods,执行bean的初始化

        ④调用applyBeanPostProcessorAfterInitialization()方法,运行所有后置处理器的postProcessAfterInitialization后置方法

    4、把BeanPostProcessor注册到BeanFactory中:beanFactory.addBeanPostProcessor(beanPostProcessor);

    以上是创建AnnotationAwareAspectJAutoProxyCreator的过程

2、完成BeanFactory的初始化工作,调用finishBeanFactoryInitialization(beanFactory)

    ①遍历获取容器中所有的bean,依次创建所有的bean,此处的创建bean是先从缓存中查询bean,查询不到才创建,以此保证单实例

    ②创建bean之前先调用resolveBeforeInstantiation(),希望后置处理器在此返回一个代理对象,如果能返回代理对象则使用该代理对象,否则继续,在此处会判断该Bean是否是InstantiationAwareBeanPostProcessor,如果是的话则会创建一个代理对象,这就是BeanPostProcessor和InstantiationAwareBeanPostProcessor的区别,BeanPostProcessor是在bean创建完成之后初始化的前后调用其前置和后置方法,而InstantiationAwareBeanPostProcessor是在创建bean之前调用的,而AnnotationAwareAspectJAutoProxyCreator父类实现了InstantiationAwareBeanPostProcessor接口,所以会返回一个代理对象,而此代理对象是在其他bean创建之前返回的,因此它可以将其方法穿插到其他bean的前后,而实现前置通知、后置通知等

    ③调用doCreateBean,真正的创建一个bean实例

        创建bean实例

       populateBean():给bean的各种属性赋值

       initializeBean():初始化bean,bean的后置处理器就是在该方法的前后工作的,初始化时

           调用invokeAwareMethods,处理Aware接口的方法回调

           调用applyBeanPostProcessorBeforeInitialization()方法,运行所有后置处理器的postProcessBeforeInitialization前置方法

           调用invokeInitMethods,执行bean的初始化

           调用applyBeanPostProcessorAfterInitialization()方法,运行所有后置处理器的postProcessAfterInitialization后置方法

你可能感兴趣的:(Spring注解驱动开发)