1、添加注解来支持spring aop
@EnableAspectJAutoProxy(proxyTargetClass = false)
2、在springboot里面, 自动支持aop,原因是spring.factories里面的
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
3、yml中添加配置支持aop(其实不添加配置也生效)
spring: aop: auto: true proxy-target-class: true
4、@EnableAspectJAutoProxy
->@Import(AspectJAutoProxyRegistrar.class)
可以看出@EnableAspectJAutoProxy引入了AspectJAutoProxyRegister.class对象 ,AspectJAutoProxyRegister给容器中注册一个AnnotationAwareAspectJAutoProxyCreator。AnnotationAwareAspectJAutoProxyCreator实现了InstantiationAwareBeanPostProcessor接口,所以每次创建bean实例前都会调用AnnotationAwareAspectJAutoProxyCreator类的postProcessBeforeInstantiation()方法。
参考博客:Spring源码阅读-AOP实现核心类AbstractAutoProxyCreator - 程小员的个人页面 - OSCHINA - 中文开源技术交流社区
4.1、Advisor的获取:
首先获取spring bean中所有的Advisor
实现了Advisor接口(从spring容器中获取实现了Advisor接口的bean);
被@Aspect修饰的类转换成Advisor(遍历spring容器的所有bean,找出被@Aspect注解标记,并且有@PointCut注解的方法,生成切点AspectJExpressionPointcut)
public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrderInAspect, String aspectName) { validate(aspectInstanceFactory.getAspectMetadata().getAspectClass()); AspectJExpressionPointcut expressionPointcut = getPointcut( candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass()); if (expressionPointcut == null) { return null; } return new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod, this, aspectInstanceFactory, declarationOrderInAspect, aspectName); }
4.2、然后判断当前bean能否被增强 findAdvisorsThatCanApply -类+任一方法满足
4.3、通过ProxyFactory创建代理对象
4.4、生成org.springframework.aop.framework.JdkDynamicAopProxy(JDK动态代理)
当调用目标类的方法时,实际是执行的jdk动态代理的invoke方法,在里面遍历advisor,判断执行方法能否被切点切到(有没有被增强),获得MethodInterceptor的数组。
MethodBeforeAdvice -> MethodBeforeAdviceInterceptor(implements MethodInterceptor)
4.5、获取方法增强的责任链
5、设计模式
工厂模式
适配器模式
责任链模式