spring aop源码解析

spring aop源码解析

示例

maven

compile(project(":spring-context"))
compile(project(":spring-webmvc"))
compile(project(":spring-aop"))
compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-core', version: '8.5.53'
// aop需要引入aspectjweaver
compile group: 'org.aspectj', name: 'aspectjweaver', version: '1.9.5'
DoSomeThing
@Component
public class DoSomeThing {

	public void doing(){
		System.out.println("doing");
	}
}
PointCut

@Aspect
@Component
public class PointCut {

	@Pointcut("execution(* aop.*.*(..))")
	public void pointCut(){ }

	@Around("pointCut()")
	public void around(ProceedingJoinPoint pjp){
		System.out.println("before");
		try {
			pjp.proceed();
		} catch (Throwable throwable) {
			throwable.printStackTrace();
		}
		System.out.println("after");
	}
}

Config
@Configuration
/**
 * true : 开启cglib
 */
@EnableAspectJAutoProxy(proxyTargetClass = false)
@ComponentScan("aop")
public class Config { }
Main
public class Main {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext configApplicationContext =
				new AnnotationConfigApplicationContext(Config.class);
		DoSomeThing bean = configApplicationContext.getBean(DoSomeThing.class);
		bean.doing();
	}
}

point:
before
doing
after

源码跟踪

20200408182059853_25993

选择代理类型 --- createProxy()

20200408182233640_5865

  1. 通过源码可知,实际上spring aop在执行上,主要在bean实例化时,先构建好bean,未填充属性之后,调用beanFactory后置处理时,执行AnnotationAwareAspectJAutoProxyCreator类的postProcessAfterInitialization(),将实例化的对象转换为代理对象
  2. 关于AnnotationAwareAspectJAutoProxyCreator的引入采用的是@EnableAspectJAutoProxy注解,内部导入@Import(AspectJAutoProxyRegistrar.class),这就是说在bd构建时,注册一个AnnotationAwareAspectJAutoProxyCreator

导入AnnotationAwareAspectJAutoProxyCreator流程

  1. EnableAspectJAutoProxy注解
    20200408183347302_21103
  2. 导入流程
    20200408183400358_24232

spring aop源码解析
https://www.blaaair.com/archives/springaop-yuan-ma-jie-xi
作者
Glo6f
发布于
2024年09月30日
许可协议