1.Spring的Aop是什么
在程序运行的时候将一乱代码切入到指定的方法的指定位置的一种编程方法
2.Spring的Aop如何使用
1) 将业务逻辑组件和切面组件都加入到容器中,告诉Spring哪个是切面类(@Aspect)
2) 在切面类上的每一个通知方法上都标注通知注解,告诉Spring是何时何地运行(切入点表达式)
3) 在配置文件或者配置类中(@Configuration)开启基于注解的Aop模式 @EnableAspectJAutoProxy
3.SpringAop的原理
3.1 @EnableAspectJAutoProxy是什么
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy
AspectJAutoProxyRegistry是ImportBeanDefinitionRegistrar的一个实现类,搭配@Import注解用户给容器中自定义注入组件。
class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
/**
* Register, escalate, and configure the AspectJ auto proxy creator based on the value
* of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing
* {@code @Configuration} class.
*/
@Override
public void registerBeanDefinitions(
AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
//这个方法将在BeanDefinitionRegistry中注入一个Bean
//internalAutoProxyCreator = AnnotationAwareAspectJAutoProxyCreator
AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
...
}
}
结论:@EnableAspectJAutoProxy给容器中注入了AnnotationAwareAspectJAutoProxyCreator组件
3.2 AnnotationAwareAspectJAutoProxyCreator的结构
首先我们需要关注两个点,一个是BeanPostProcessor,另外一个是BeanFactoryAware.
BeanFactoryAware中有个核心的方法setBeanFactory Spring容器会通过反射传进一个BeanFactory参数,但是这个方法被AbstractProxyCreator然后被AspectAdvisorAutoProxyCreator所覆盖,所以覆盖后的setBeanFactory方法执行的是
AspectAdvisorAutoProxyCreator类的setBeanFactory方法
public void setBeanFactory(BeanFactory beanFactory) {
//进行一些基本的赋值
super.setBeanFactory(beanFactory);
if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
throw new IllegalArgumentException("AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory);
} else {
this.initBeanFactory((ConfigurableListableBeanFactory)beanFactory);
}
}
然后我们可以看到 AspectAdvisorAutoProxyCreator的setBeanFactory执行了super.setBeanFactory(beanFactory);这个父类方法只是进行了进行一些简单的赋值操作,然后执行后面的AnnotationAwareAspectJAutoProxyCreator类initBeanFactory方法,
AnnotationAwareAspectJAutoProxyCreator类
protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.initBeanFactory(beanFactory);
if (this.aspectJAdvisorFactory == null) {
this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory);
}
this.aspectJAdvisorsBuilder = new AnnotationAwareAspectJAutoProxyCreator.BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);
}
3.3 跟踪Spring容器启动,查看Spring容器时做了什么
流程: 1) 传入配置类 ,创建IOC容器
2) 注册配置类 , 调用refresh()刷新容器
public void refresh(){
// 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);
// 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
//注册BeanPostProcessor完成来拦截的bean创建.
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();
}
这里的
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
/**1.获取ioc容器中已经定义的需要创建的BeanPostProcessor,例如
AutowiredAnnotationProcessor(完成Autowired注解的解析) CommonAnnotationProcessor
InternalAutoProxyCreator(@EnableAspectJAutoProxy所导入的组件) **/
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
...
//2. 将所有的BeanPostProcessor分成三类 PriorityOrderedProcessor,OrderedProcessor,
Rest
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
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);
}
}
//3.分别对不桶类别的BeanPostProcessor分别进行处理
// First, register the BeanPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
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<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
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));
}
由上面的代码得知RegisterBeanPostProcessors()方法的作用是取出所有的BeanPostProcessor 看看这些BeanPostProcessor是实现了PriorityOrder还是Order 或者是没有 , 将他们进行分类, 排序,创建 ,最后
未完待续。。。。