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
源码跟踪
选择代理类型 --- createProxy()
- 通过源码可知,实际上spring aop在执行上,主要在bean实例化时,先构建好bean,未填充属性之后,调用beanFactory后置处理时,执行
AnnotationAwareAspectJAutoProxyCreator
类的postProcessAfterInitialization(),将实例化的对象转换为代理对象- 关于
AnnotationAwareAspectJAutoProxyCreator
的引入采用的是@EnableAspectJAutoProxy注解,内部导入@Import(AspectJAutoProxyRegistrar.class),这就是说在bd构建时,注册一个AnnotationAwareAspectJAutoProxyCreator
导入AnnotationAwareAspectJAutoProxyCreator流程
- EnableAspectJAutoProxy注解
- 导入流程
spring aop源码解析
https://www.blaaair.com/archives/springaop-yuan-ma-jie-xi