注:其他一些spring源码解读,如果有需要,可以参考:
spring的AOP是什么不在赘述,以下内容默认大家会使用AOP,我们今天来扒源码
org.springframework
spring-context
4.3.12.RELEASE
junit
junit
4.12
org.springframework
spring-aspects
4.2.2.RELEASE
/**
* todo
*
* @author wangjie
* @version V1.0
* @date 2020/1/7
*/
public class MathCalculator {
public int test(int i,int j){
return i/j;
}
}
/**
* 日志切面
* @Aspect: 告诉Spring当前类是一个切面类
* @author wangjie
* @version V1.0
* @date 2020/1/7
*/
@Aspect
public class LogAspects {
/**
* 抽取公共的切入点表达式
* 1、本类引用
* 2、其他的切面引用
*/
@Pointcut("execution(public int com.code.aop.MathCalculator.*(..))")
public void pointCut(){};
@Before("pointCut()")
public void logStart(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();
System.out.println(""+joinPoint.getSignature().getName()+"运行。。。@Before:参数列表是:{"+ Arrays.asList(args)+"}");
}
@After("pointCut()")
public void logEnd(JoinPoint joinPoint){
System.out.println(""+joinPoint.getSignature().getName()+"结束。。。@After");
}
/**
* JoinPoint一定要出现在参数表的第一位
* @param joinPoint
* @param result
*/
@AfterReturning(value="pointCut()",returning="result")
public void logReturn(JoinPoint joinPoint,Object result){
System.out.println(""+joinPoint.getSignature().getName()+"正常返回。。。@AfterReturning:运行结果:{"+result+"}");
}
@AfterThrowing(value="pointCut()",throwing="exception")
public void logException(JoinPoint joinPoint,Exception exception){
System.out.println(""+joinPoint.getSignature().getName()+"异常。。。异常信息:{"+exception+"}");
}
}
Configuration
@EnableAspectJAutoProxy
public class AOPConfig {
@Bean
public MathCalculator mathCalculator(){
return new MathCalculator();
}
@Bean
public LogAspects logAspects(){
return new LogAspects();
}
}
/**
* todo
*
* @author wangjie
* @version V1.0
* @date 2020/1/7
*/
public class IOCTest_AOP {
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AOPConfig.class);
MathCalculator mathCalculator = applicationContext.getBean(MathCalculator.class);
mathCalculator.test(1, 1);
mathCalculator.test(1, 0);
applicationContext.close();
}
}
test运行。。。@Before:参数列表是:{[1, 1]}
test结束。。。@After
test正常返回。。。@AfterReturning:运行结果:{1}
test运行。。。@Before:参数列表是:{[1, 0]}
test结束。。。@After
test异常。。。异常信息:{java.lang.ArithmeticException: / by zero}
java.lang.ArithmeticException: / by zero
at com.code.aop.MathCalculator.test(MathCalculator.java:13)
at com.code.aop.MathCalculator$$FastClassBySpringCGLIB$$96b23dea.invoke()
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
省略多余异常信息。。。。
Process finished with exit code -1
具体源码太过繁杂,正式扒源码之前,我们先以上帝视角对AOP流程做个概述,以下流程涉及的所有类和方法具体解释我们在下个章节慢慢聊。
正常执行:前置通知-》目标方法-》后置通知-》返回通知
出现异常:前置通知-》目标方法-》后置通知-》异常通知
3.1 @EnableAspectJAutoProxy分析
class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar
public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {...}
public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {...}
public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {...}
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {.....}
public interface BeanFactoryAware extends Aware {
void setBeanFactory(BeanFactory var1) throws BeansException;
}
3.2 AOP原理分析
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AOPConfig.class);
public AnnotationConfigApplicationContext(Class... annotatedClasses) {
this();
//解析配置类,注册bean
this.register(annotatedClasses);
//spring的核心,在这个方法里,Spring完成了容器的初始化
this.refresh();
}
public void refresh() throws BeansException, IllegalStateException {
Object var1 = this.startupShutdownMonitor;
synchronized(this.startupShutdownMonitor) {
//容器刷新前的准备,设置上下文状态,获取属性,验证必要的属性等
this.prepareRefresh();
//获取新的beanFactory,销毁原有beanFactory、为每个bean生成BeanDefinition等
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
//配置标准的beanFactory,设置ClassLoader,设置SpEL表达式解析器,添加忽略注入的接口,添加bean,添加bean后置处理器等
this.postProcessBeanFactory(beanFactory);
//模板方法,此时,所有的beanDefinition已经加载,但是还没有实例化。
//允许在子类中对beanFactory进行扩展处理。比如添加ware相关接口自动装配设置,添加后置处理器等,是子类扩展
//prepareBeanFactory(beanFactory)的方法。
// 实例化并调用所有注册的beanFactory后置处理器(实现接口BeanFactoryPostProcessor的bean,在beanFactory标准初始化之后执行)。
this.invokeBeanFactoryPostProcessors(beanFactory);
//实例化和注册beanFactory中扩展了BeanPostProcessor的bean。
this.registerBeanPostProcessors(beanFactory);
//初始化国际化工具类MessageSource
this.initMessageSource();
//初始化事件广播器
this.initApplicationEventMulticaster();
//模板方法,在容器刷新的时候可以自定义逻辑,不同的Spring容器做不同的事情。
this.onRefresh();
//注册监听器,广播early application events
this.registerListeners();
//实例化所有剩余的(非懒加载)单例
//实例化的过程各种BeanPostProcessor开始起作用。
this.finishBeanFactoryInitialization(beanFactory);
//refresh做完之后需要做的其他事情。
//清除上下文资源缓存(如扫描中的ASM元数据)
//初始化上下文的生命周期处理器,并刷新(找出Spring容器中实现了Lifecycle接口的bean并执行start()方法)。
//发布ContextRefreshedEvent事件告知对应的ApplicationListener进行响应的操作
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
//先获取ioc容器已经定义了的需要创建对象的所有BeanPostProcessor
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
//给容器中加别的BeanPostProcessor
beanFactory.addBeanPostProcessor(new PostProcessorRegistrationDelegate.BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
List priorityOrderedPostProcessors = new ArrayList();
List internalPostProcessors = new ArrayList();
List orderedPostProcessorNames = new ArrayList();
List nonOrderedPostProcessorNames = new ArrayList();
String[] var8 = postProcessorNames;
int var9 = postProcessorNames.length;
String ppName;
BeanPostProcessor pp;
for(int var10 = 0; var10 < var9; ++var10) {
ppName = var8[var10];
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
pp = (BeanPostProcessor)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);
}
}
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, (List)priorityOrderedPostProcessors);
List orderedPostProcessors = new ArrayList();
Iterator var14 = orderedPostProcessorNames.iterator();
while(var14.hasNext()) {
String ppName = (String)var14.next();
BeanPostProcessor pp = (BeanPostProcessor)beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, (List)orderedPostProcessors);
List nonOrderedPostProcessors = new ArrayList();
Iterator var17 = nonOrderedPostProcessorNames.iterator();
while(var17.hasNext()) {
ppName = (String)var17.next();
pp = (BeanPostProcessor)beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, (List)nonOrderedPostProcessors);
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, (List)internalPostProcessors);
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
public class ProxyProcessorSupport extends ProxyConfig implements Ordered, BeanClassLoaderAware, AopInfrastructureBean {
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);
}
}
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);
}
public void refresh() throws BeansException, IllegalStateException {
Object var1 = this.startupShutdownMonitor;
synchronized(this.startupShutdownMonitor) {
//容器刷新前的准备,设置上下文状态,获取属性,验证必要的属性等
this.prepareRefresh();
//获取新的beanFactory,销毁原有beanFactory、为每个bean生成BeanDefinition等
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
//配置标准的beanFactory,设置ClassLoader,设置SpEL表达式解析器,添加忽略注入的接口,添加bean,添加bean后置处理器等
this.postProcessBeanFactory(beanFactory);
//模板方法,此时,所有的beanDefinition已经加载,但是还没有实例化。
//允许在子类中对beanFactory进行扩展处理。比如添加ware相关接口自动装配设置,添加后置处理器等,是子类扩展
//prepareBeanFactory(beanFactory)的方法。
// 实例化并调用所有注册的beanFactory后置处理器(实现接口BeanFactoryPostProcessor的bean,在beanFactory标准初始化之后执行)。
this.invokeBeanFactoryPostProcessors(beanFactory);
//实例化和注册beanFactory中扩展了BeanPostProcessor的bean。
this.registerBeanPostProcessors(beanFactory);
//初始化国际化工具类MessageSource
this.initMessageSource();
//初始化事件广播器
this.initApplicationEventMulticaster();
//模板方法,在容器刷新的时候可以自定义逻辑,不同的Spring容器做不同的事情。
this.onRefresh();
//注册监听器,广播early application events
this.registerListeners();
//实例化所有剩余的(非懒加载)单例
//实例化的过程各种BeanPostProcessor开始起作用。
this.finishBeanFactoryInitialization(beanFactory);
//refresh做完之后需要做的其他事情。
//清除上下文资源缓存(如扫描中的ASM元数据)
//初始化上下文的生命周期处理器,并刷新(找出Spring容器中实现了Lifecycle接口的bean并执行start()方法)。
//发布ContextRefreshedEvent事件告知对应的ApplicationListener进行响应的操作
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
3.3 目标方法的执行