继续源码学习,看了spring中基础的容器和AOP感觉自己也没有什么长进,哈哈,我也不知道到底有用没有,这可能是培养自己的一种精神吧,不管那么多,继续学习!AOP中

AOP中几个重要的概念:
(1)Advice--通知
Advice定义在连接点做什么,为切面增强提供织入接口。在spring中,他主要描述spring AOP围绕方法调用而注入的切面行为。在spring AOP的实现中,使用了AOP联盟定义的统一接口--Advice接口并通过这个接口,为AOP切面的增强的织入功能做了更多的细话和扩展
(2)PonitCut--切点
PonitCut(切点)决定Advice通知应该作用于哪个连接点,也就是说通过PonitCut来定义需要增强的方法的集合。这些集合的选取可以按照一定的规则来完成。这种情况下,PonitCut通常意味着标识方法,例如,这些需要增强的地方可以由某个正则表达式进行标识,或根据某个方法名进行匹配
(3)Advisor--通知器
完成对目标方法的切面增强设计(Advice)和关注点的设计(PointCut)以后,需要一个对象把它们结合起来,完成这个作用的就是Advisor,通过Advisor,可以定义在应该使用哪个通知并在哪个关注点使用它,也就是说通过Advisor,把Advice和PointCut结合起来,这个结合为使用IoC容器配置AOP应用,或者说即开即用地使用AOP基础设施,提供了便利

一、动态AOP的使用案例

1、创建用于拦截的bean
test方法中封装这核心业务,想在test前后加入日志来跟踪调试,这时候可以使用spring中提供的AOP功能来实现

 public class TestBean(){
private String testStr = "testStr"; public void setTestStr(String testStr){
this.testStr = testStr;
} public String getTestStr(){
rerurn testStr;
} public void test(){
System.out.println("test");
}
}

2、创建Advisor
spring中使用注解的方式实现AOP功能,简化了配置

 @Aspect
public class AspectJTest{ @Pointcut("execution(* *.test(..))")
public void test(){ } @Before("test()")
public void beforeTest(){
System.out.println("beforeTest");
} @AfterTest("test()")
public void afterTest(){
System.out.println("afterTest");
} @Around("test()")
public Object aroundTest(ProceedingJoinPoint p){
System.out.println("before1");
Object o = null;
o = p.proceed();
System.out.println("after1");
return o;
}
}

3、创建配置文件
XML是Spring的基础。尽管Spring一再简化配置,并且大有使用注解取代XML配置之势,但是在spring中开启AOP功能,还需配置一些信息

 <aop:aspectj-autoproxy />
<bean id="test" class="test.TestBean"/>
<bean class="test.AspectJTest"/>

4、测试

 public static void main(String[] args){
ApplicationContext bf = new ClassPathXmlApplicationContext("aspectTest.xml");
TestBean bean = bf.getBean("test");
bean.test();
}

那么,spring是如何实现AOP的呢?spring是否支持注解的AOP由一个配置文件控制的,<aop:aspectj-autoproxy />,当在spring的配置文件中声明这句配置的时候,
spring就会支持注解的AOP,从这个注解开始分析

二、动态AOP自定义标签

全局搜索一下aspectj-autoproxy,在org.springframework.aop.config包下的AopNamespaceHandler类中发现了:

 @Override
public void init() {
// In 2.0 XSD as well as in 2.1 XSD.
registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser());
registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());
registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator()); // Only in 2.0 XSD: moved to context namespace as of 2.1
registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
}

这里的解析aspectj-autoproxy标签的解析器是AspectJAutoProxyBeanDefinitionParser,看一下这个类的内部实现

1、注册AspectJAutoProxyBeanDefinitionParser

所有解析器,因为是对BeanDefinitionParser接口的实现,入口都是从parse函数开始的,从AspectJAutoProxyBeanDefinitionParser的parse方法来看:

 @Override
@Nullable
public BeanDefinition parse(Element element, ParserContext parserContext) {
// 注册一个类型为AnnotationAwareAspectJAutoProxyCreator的bean到Spring容器中
AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);
// 对于注解中子类的处理
extendBeanDefinition(element, parserContext);
return null;
}

看一下registerAspectJAnnotationAutoProxyCreatorIfNecessary方法中逻辑的实现:

 public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary(
ParserContext parserContext, Element sourceElement) { // 注册AnnotationAwareAspectJAutoProxyCreator的BeanDefinition
BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(
parserContext.getRegistry(), parserContext.extractSource(sourceElement));
// 解析标签中的proxy-target-class和expose-proxy属性值,
// proxy-target-class主要控制是使用Jdk代理还是Cglib代理实现,expose-proxy用于控制
// 是否将生成的代理类的实例防御AopContext中,并且暴露给相关子类使用
useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement);
// 将注册的BeanDefinition封装到BeanComponentDefinition中,注册组件并监听,便于监听器做进一步处理
registerComponentIfNecessary(beanDefinition, parserContext);
}

看一下具体的逻辑代码:主要是分三部分,基本没一行代码都是代表着一部分逻辑

(1)注册或者升级AnnotationAwareAspectJAutoProxyCreator
对于AOP实现,基本上都是靠AnnotationAwareAspectJAutoProxyCreator去完成的,为了方便,spring使用了自定义配置来帮助我们自动注册AnnotationAwareAspectJAutoProxyCreator
起源吗主要是这样的:
org.springframework.aop.config包下的AopConfigUtils类中

 @Nullable
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(
BeanDefinitionRegistry registry, @Nullable Object source) { return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
} 同一个类中:
@Nullable
private static BeanDefinition registerOrEscalateApcAsRequired(
Class<?> cls, BeanDefinitionRegistry registry, @Nullable Object source) { Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); // 如果已经存在了自动代理创建器且存在的自动代理创建器与现在的不一致,那么需要根据优先级来判断到底需要使用哪个
if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
// AUTO_PROXY_CREATOR_BEAN_NAME = "org.springframework.aop.config.internalAutoProxyCreator"
BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
int requiredPriority = findPriorityForClass(cls);
if (currentPriority < requiredPriority) {
// 改变bean最重要的是改变bean所对应的className属性
apcDefinition.setBeanClassName(cls.getName());
}
}
// 如果已经存在自动代理创造器并且与将要创建的一致,那么无须再次创建
return null;
} RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
beanDefinition.setSource(source);
beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
return beanDefinition;
}

(2)处理proxy-target-class和expose-proxy属性
org.springframework.aop.config包下的AopNamespaceHandler类useClassProxyingIfNecessary方法

 private static void useClassProxyingIfNecessary(BeanDefinitionRegistry registry, @Nullable Element sourceElement) {
if (sourceElement != null) {
// 对于proxy-target-class属性的处理
boolean proxyTargetClass = Boolean.parseBoolean(sourceElement.getAttribute(PROXY_TARGET_CLASS_ATTRIBUTE));
if (proxyTargetClass) {
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
}
// 对于 expose-proxy属性的处理
boolean exposeProxy = Boolean.parseBoolean(sourceElement.getAttribute(EXPOSE_PROXY_ATTRIBUTE));
if (exposeProxy) {
AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
}
}
}

org.springframework.aop.config包下的AopConfigUtils类中forceAutoProxyCreatorToUseClassProxying方法和forceAutoProxyCreatorToExposeProxy方法

 // 强制使用的过程也是属性设置的过程
public static void forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistry registry) {
if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
definition.getPropertyValues().add("proxyTargetClass", Boolean.TRUE);
}
} public static void forceAutoProxyCreatorToExposeProxy(BeanDefinitionRegistry registry) {
if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
definition.getPropertyValues().add("exposeProxy", Boolean.TRUE);
}
}

proxy-target-class属性:Spring AOP部分使用JDK动态代理或者CGLIB来为目标对象创建代理(建议尽量使用JDK的动态代理),如果目标对象实现了至少一个接口,
则会使用JDK动态代理,所有该目标被实现的接口都将被代理,若该目标对象没有实现任何接口,则创建一个CGLIB代理。
强制使用CGLIB代理需要将proxy-target-class属性设置为true

实际使用中发现的使用中的差别:
JDK动态代理:
其代理对象必须是某个接口的实现,他是通过在运行期间创建一个接口的实现类来完成对目标对象的代理
CGLIB代理:
实现原理类似于JDK动态代理,只是他在运行期间生成的代理对象是针对目标类扩展的子类,CGLIB是高效的代码生成包,底层是依靠ASM操作字节码实现的,性能比JDK强

expose-proxy属性:
有时候目标对象内部的自我调用将无法实施切面中的增强

(3)将注册的BeanDefinition封装到BeanComponentDefinition中

org.springframework.aop.config包下的AopNamespaceHandler类中的registerComponentIfNecessary方法

 private static void registerComponentIfNecessary(@Nullable BeanDefinition beanDefinition, ParserContext parserContext) {
if (beanDefinition != null) {
parserContext.registerComponent(
new BeanComponentDefinition(beanDefinition, AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME));
}
}

三、创建AOP代理

  上文中讲解了通过自定义配置完成了对AnnotationAwareAspectJAutoProxyCreator的注册,那么这个类到底做了什么工作来完成AOP工作的,可以看一下AnnotationAwareAspectJAutoProxyCreator类的层次结构,我们可以看到AnnotationAwareAspectJAutoProxyCreator实现了BeanPostProcessor接口,当spring加载这个Bean的时候会在实例化前调用其postProcessAfterInitialization,从这个开始

org.springframework.aop.framework.autoproxy包下的AbstractAutoProxyCreator,看一下父类这个postProcessAfterInitialization方法

 @Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
if (bean != null) {
// 根据给定的bean的class和name构建出一个key,格式beanClassName_beanName
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
// 如果它适合被代理,则需封装指定bean
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
} // 同一个类中:
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
// 如果已经处理过
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
// 无需增强
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
}
// 给定的bean类是否代表一个基础施设类,基础设施类不应代理或者配置了指定类不需要自动代理
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
} // Create proxy if we have advice.
// 如果存在增强方法则创建代理
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
// 如果获取到了增强,则需要根据增强创建代理
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
// 创建代理
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
} this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}

函数中,我们已经看到了代理创建的雏形,在创建之前还需要经过一些判断,比如,是否已经处理过或者是否需要跳过的bean,而真正创建代理的代码是从getAdvicesAndAdvisorsForBean方法开始的
创建代理的逻辑主要分为两部分:
(1)获取增强方法或者增强器
(2)根据获取的增强进行代理

org.springframework.aop.framework.autoproxy包下的AbstractAdvisorAutoProxyCreator类中

 @Override
@Nullable
protected Object[] getAdvicesAndAdvisorsForBean(
Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) { List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
if (advisors.isEmpty()) {
return DO_NOT_PROXY;
}
return advisors.toArray();
} protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
// 获取增强器
List<Advisor> candidateAdvisors = findCandidateAdvisors();
// 寻找匹配的增强器
List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
extendAdvisors(eligibleAdvisors);
if (!eligibleAdvisors.isEmpty()) {
eligibleAdvisors = sortAdvisors(eligibleAdvisors);
}
return eligibleAdvisors;
}

对于指定bean的增强方法的获取一定是包含两个步骤,获取所有的增强以及寻找所有增强中适用于bean的增强并应用,那么findCandidateAdvisors和findAdvisorsThatCanApply
便是做了这两件事情

1、获取增强器

由于我们分析的是使用注解进行的AOP,所以对于findCandidateAdvisors的实现其实是由org.springframework.aop.aspectj.annotation包下的AnnotationAwareAspectJAutoProxyCreator完成的,继续跟踪此类中的findCandidateAdvisors方法

 @Override
protected List<Advisor> findCandidateAdvisors() {
// Add all the Spring advisors found according to superclass rules.
// 当使用注解方式配置AOP的时候并不是丢弃了对XML配置的支持
// 这里调用父类方法加载配置文件中的AOP声明
List<Advisor> advisors = super.findCandidateAdvisors();
// Build Advisors for all AspectJ aspects in the bean factory.
if (this.aspectJAdvisorsBuilder != null) {
advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
}
return advisors;
}

AnnotationAwareAspectJAutoProxyCreator简接继承了AbstractAdvisorAutoProxyCreator,在实现获取增强的方法中除了保留父类的获取配置文件中定义的增强外,
同时添加了获取Bean的注解增强的功能,那么其实正是由this.aspectJAdvisorsBuilder.buildAspectJAdvisors();来实现的。思路如下:
(1)获取所有的beanName,这一步骤中所有在beanFactory中注册的bean都会被提取出来
(2)遍历所有的beanName,并找出声明AspectJ注解的类,进行进一步处理
(3)对标记AspectJ注解的类进行增强器的提取
(4)将提取结果加入缓存

看看源码如何实现AspectJ注解增强处理:提取Advisor
org.springframework.aop.aspectj.annotation包下的BeanFactoryAspectJAdvisorsBuilder类中的buildAspectJAdvisors方法

 public List<Advisor> buildAspectJAdvisors() {
List<String> aspectNames = this.aspectBeanNames; if (aspectNames == null) {
synchronized (this) {
aspectNames = this.aspectBeanNames;
if (aspectNames == null) {
List<Advisor> advisors = new ArrayList<>();
aspectNames = new ArrayList<>();
// 获取所有的beanName
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Object.class, true, false);
// 循环所有的beanName找出对应的增强方法
for (String beanName : beanNames) {
// 不合法的bean略过,又子类定义规则,默认返回true
if (!isEligibleBean(beanName)) {
continue;
}
// We must be careful not to instantiate beans eagerly as in this case they
// would be cached by the Spring container but would not have been weaved.
// 获取对应的bean类型
Class<?> beanType = this.beanFactory.getType(beanName);
if (beanType == null) {
continue;
}
// 如果存在AspectJ注解
if (this.advisorFactory.isAspect(beanType)) {
aspectNames.add(beanName);
AspectMetadata amd = new AspectMetadata(beanType, beanName);
//
if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
MetadataAwareAspectInstanceFactory factory =
new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
// 解析标记AspectJ注解中的增强方法
List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);
if (this.beanFactory.isSingleton(beanName)) {
this.advisorsCache.put(beanName, classAdvisors);
}
else {
this.aspectFactoryCache.put(beanName, factory);
}
advisors.addAll(classAdvisors);
}
else {
// Per target or per this.
if (this.beanFactory.isSingleton(beanName)) {
throw new IllegalArgumentException("Bean with name '" + beanName +
"' is a singleton, but aspect instantiation model is not singleton");
}
MetadataAwareAspectInstanceFactory factory =
new PrototypeAspectInstanceFactory(this.beanFactory, beanName);
this.aspectFactoryCache.put(beanName, factory);
advisors.addAll(this.advisorFactory.getAdvisors(factory));
}
}
}
this.aspectBeanNames = aspectNames;
return advisors;
}
}
} if (aspectNames.isEmpty()) {
return Collections.emptyList();
}
// 记录在缓存中
List<Advisor> advisors = new ArrayList<>();
for (String aspectName : aspectNames) {
List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName);
if (cachedAdvisors != null) {
advisors.addAll(cachedAdvisors);
}
else {
MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName);
advisors.addAll(this.advisorFactory.getAdvisors(factory));
}
}
return advisors;
}

至此已经完成了Advisor的提取,在上面的步骤中最为重要的,也是最为复杂的就是增强器的获取。而这一功能委托给this.advisorFactory.getAdvisors(factory)
看一下这个方法的源码中逻辑是如何实现的:
org.springframework.aop.aspectj.annotation包下的ReflectiveAspectJAdvisorFactory类中

 @Override
public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {
// 获取标记为AspectJ的类
Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
// 获取标记为AspectJ的name
String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();
// 验证
validate(aspectClass); // We need to wrap the MetadataAwareAspectInstanceFactory with a decorator
// so that it will only instantiate once.
MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =
new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory); List<Advisor> advisors = new ArrayList<>();
// getAdvisorMethods方法中利用反射来获取Advisor中所有的方法,spring中做了一部分处理
for (Method method : getAdvisorMethods(aspectClass)) {
Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName);
if (advisor != null) {
advisors.add(advisor);
}
} // If it's a per target aspect, emit the dummy instantiating aspect.
if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
// 如果寻找的增强器不为空而且又配置了增强延迟的初始化,那么需要在首位加入同步实例化增强器
Advisor instantiationAdvisor = new SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);
advisors.add(0, instantiationAdvisor);
} // Find introduction fields.
// 获取DeclareParents注解
for (Field field : aspectClass.getDeclaredFields()) {
Advisor advisor = getDeclareParentsAdvisor(field);
if (advisor != null) {
advisors.add(advisor);
}
} return advisors;
} // getAdvisorMethods方法在spring5.0 中是封装到一个单独的方法中去了,作者书中的源码并没有进行封装
private List<Method> getAdvisorMethods(Class<?> aspectClass) {
final List<Method> methods = new ArrayList<>();
ReflectionUtils.doWithMethods(aspectClass, method -> {
// Exclude pointcuts
// 声明为Pointcut的方法不处理
if (AnnotationUtils.getAnnotation(method, Pointcut.class) == null) {
methods.add(method);
}
});
methods.sort(METHOD_COMPARATOR);
return methods;
}

函数中首先完成了对增强器的获取,包括获取注解以及根据注解生成增强的步骤,然后考虑到在配置中可能会将增强配置成延迟初始化,那么需要在首位加入同步
实例化增强器以保证增强使用之前的实例化,最后是对DeclareParents注解的获取

(1)普通增强器的获取

普通增强器的获取逻辑是通过getAdvisor方法实现的,实现步骤包括对切入的注解的获取以及根据注解信息生成增强

org.springframework.aop.aspectj.annotation包下的ReflectiveAspectJAdvisorFactory类中

 @Override
@Nullable
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);
}

1.1 切点信息的获取,这个就是指定注解的表达式信息的获取,如Befor("test()")
org.springframework.aop.aspectj.annotation包下的ReflectiveAspectJAdvisorFactory类中

 @Nullable
private AspectJExpressionPointcut getPointcut(Method candidateAdviceMethod, Class<?> candidateAspectClass) {
// 获取方法上的注解
AspectJAnnotation<?> aspectJAnnotation =
AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);
if (aspectJAnnotation == null) {
return null;
} // AspectJExpressionPointcut来封装获取到的信息
AspectJExpressionPointcut ajexp =
new AspectJExpressionPointcut(candidateAspectClass, new String[0], new Class<?>[0]);
// 提取得到的注解中的表达式 如@Before("test()") 中的 test()
ajexp.setExpression(aspectJAnnotation.getPointcutExpression());
if (this.beanFactory != null) {
ajexp.setBeanFactory(this.beanFactory);
}
return ajexp;
}

org.springframework.aop.aspectj.annotation包下的ReflectiveAspectJAdvisorFactory类中

 @SuppressWarnings("unchecked")
@Nullable
protected static AspectJAnnotation<?> findAspectJAnnotationOnMethod(Method method) {
// 设置敏感的注解类
for (Class<?> clazz : ASPECTJ_ANNOTATION_CLASSES) {
AspectJAnnotation<?> foundAnnotation = findAnnotation(method, (Class<Annotation>) clazz);
if (foundAnnotation != null) {
return foundAnnotation;
}
}
return null;
}

org.springframework.aop.aspectj.annotation包下的ReflectiveAspectJAdvisorFactory类中

 // 获取指定方法上的注解并使用AspectJAnnotation封装
@Nullable
private static <A extends Annotation> AspectJAnnotation<A> findAnnotation(Method method, Class<A> toLookFor) {
A result = AnnotationUtils.findAnnotation(method, toLookFor);
if (result != null) {
return new AspectJAnnotation<>(result);
}
else {
return null;
}
}

1.2 根据切点信息生成增强,所有的增强都是由Advisor的实现类InstantiationModelAwarePointcutAdvisorImpl统一封装的

org.springframework.aop.aspectj.annotation包下的InstantiationModelAwarePointcutAdvisorImpl类的构造方法

 public InstantiationModelAwarePointcutAdvisorImpl(AspectJExpressionPointcut declaredPointcut,
Method aspectJAdviceMethod, AspectJAdvisorFactory aspectJAdvisorFactory,
MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) { this.declaredPointcut = declaredPointcut;
this.declaringClass = aspectJAdviceMethod.getDeclaringClass();
this.methodName = aspectJAdviceMethod.getName();
this.parameterTypes = aspectJAdviceMethod.getParameterTypes();
this.aspectJAdviceMethod = aspectJAdviceMethod;
this.aspectJAdvisorFactory = aspectJAdvisorFactory;
this.aspectInstanceFactory = aspectInstanceFactory;
this.declarationOrder = declarationOrder;
this.aspectName = aspectName; if (aspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
// Static part of the pointcut is a lazy type.
Pointcut preInstantiationPointcut = Pointcuts.union(
aspectInstanceFactory.getAspectMetadata().getPerClausePointcut(), this.declaredPointcut); // Make it dynamic: must mutate from pre-instantiation to post-instantiation state.
// If it's not a dynamic pointcut, it may be optimized out
// by the Spring AOP infrastructure after the first evaluation.
this.pointcut = new PerTargetInstantiationModelPointcut(
this.declaredPointcut, preInstantiationPointcut, aspectInstanceFactory);
this.lazy = true;
}
else {
// A singleton aspect.
this.pointcut = this.declaredPointcut;
this.lazy = false;
this.instantiatedAdvice = instantiateAdvice(this.declaredPointcut);
}
}

在封装过程中只是简单地将信息封装在类的实例中,所有的信息单纯的赋值,在实例初始化的过程中,还完成了对于增强器的初始化。因为不同的增强所体现的逻辑是不同的
比如,@Before("test()")、@After("test()")标签的不同就是增强的位置不同,所以就需要不同的增强逻辑,而这部分逻辑实现是在instantiateAdvice方法中实现的

org.springframework.aop.aspectj.annotation包下的InstantiationModelAwarePointcutAdvisorImpl类中

 private Advice instantiateAdvice(AspectJExpressionPointcut pointcut) {
Advice advice = this.aspectJAdvisorFactory.getAdvice(this.aspectJAdviceMethod, pointcut,
this.aspectInstanceFactory, this.declarationOrder, this.aspectName);
return (advice != null ? advice : EMPTY_ADVICE);
} // getAdvice方法的实现是在org.springframework.aop.aspectj.annotation包下的ReflectiveAspectJAdvisorFactory类中 @Override
@Nullable
public Advice getAdvice(Method candidateAdviceMethod, AspectJExpressionPointcut expressionPointcut,
MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) { Class<?> candidateAspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
validate(candidateAspectClass); AspectJAnnotation<?> aspectJAnnotation =
AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);
if (aspectJAnnotation == null) {
return null;
} // If we get here, we know we have an AspectJ method.
// Check that it's an AspectJ-annotated class
if (!isAspect(candidateAspectClass)) {
throw new AopConfigException("Advice must be declared inside an aspect type: " +
"Offending method '" + candidateAdviceMethod + "' in class [" +
candidateAspectClass.getName() + "]");
} if (logger.isDebugEnabled()) {
logger.debug("Found AspectJ method: " + candidateAdviceMethod);
} AbstractAspectJAdvice springAdvice; // 根据不同的增强类型封装不同的增强器
switch (aspectJAnnotation.getAnnotationType()) {
case AtPointcut:
if (logger.isDebugEnabled()) {
logger.debug("Processing pointcut '" + candidateAdviceMethod.getName() + "'");
}
return null;
case AtAround:
springAdvice = new AspectJAroundAdvice(
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
break;
case AtBefore:
springAdvice = new AspectJMethodBeforeAdvice(
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
break;
case AtAfter:
springAdvice = new AspectJAfterAdvice(
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
break;
case AtAfterReturning:
springAdvice = new AspectJAfterReturningAdvice(
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
AfterReturning afterReturningAnnotation = (AfterReturning) aspectJAnnotation.getAnnotation();
if (StringUtils.hasText(afterReturningAnnotation.returning())) {
springAdvice.setReturningName(afterReturningAnnotation.returning());
}
break;
case AtAfterThrowing:
springAdvice = new AspectJAfterThrowingAdvice(
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
AfterThrowing afterThrowingAnnotation = (AfterThrowing) aspectJAnnotation.getAnnotation();
if (StringUtils.hasText(afterThrowingAnnotation.throwing())) {
springAdvice.setThrowingName(afterThrowingAnnotation.throwing());
}
break;
default:
throw new UnsupportedOperationException(
"Unsupported advice type on method: " + candidateAdviceMethod);
} // Now to configure the advice...
springAdvice.setAspectName(aspectName);
springAdvice.setDeclarationOrder(declarationOrder);
String[] argNames = this.parameterNameDiscoverer.getParameterNames(candidateAdviceMethod);
if (argNames != null) {
springAdvice.setArgumentNamesFromStringArray(argNames);
}
springAdvice.calculateArgumentBindings(); return springAdvice;
}

spring会根据不同的注解生成不同的增强器,例如@Before对应的就是AspectJMethodBeforeAdvice增强器,这里有几个增强器的详解:

第一个:MethodBeforeAdviceInterceptor,不知道为啥是这个,为什么不是AspectJMethodBeforeAdvice类
org.springframework.aop.framework.adapter包下的MethodBeforeAdviceInterceptor类

 public class MethodBeforeAdviceInterceptor implements MethodInterceptor, BeforeAdvice, Serializable {

     private final MethodBeforeAdvice advice;

     /**
* Create a new MethodBeforeAdviceInterceptor for the given advice.
* @param advice the MethodBeforeAdvice to wrap
*/
public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
Assert.notNull(advice, "Advice must not be null");
this.advice = advice;
} @Override
public Object invoke(MethodInvocation mi) throws Throwable {
this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
return mi.proceed();
} } // 其中MethodBeforeAdvice属性代表着前置增强的AspectJMethodBeforeAdvice,跟踪before方法 org.springframework.aop.aspectj包下的AspectJMethodBeforeAdvice方法
@Override
public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
invokeAdviceMethod(getJoinPointMatch(), null, null);
} protected Object invokeAdviceMethod(
@Nullable JoinPointMatch jpMatch, @Nullable Object returnValue, @Nullable Throwable ex)
throws Throwable { return invokeAdviceMethodWithGivenArgs(argBinding(getJoinPoint(), jpMatch, returnValue, ex));
} protected Object invokeAdviceMethodWithGivenArgs(Object[] args) throws Throwable {
Object[] actualArgs = args;
if (this.aspectJAdviceMethod.getParameterCount() == 0) {
actualArgs = null;
}
try {
ReflectionUtils.makeAccessible(this.aspectJAdviceMethod);
// TODO AopUtils.invokeJoinpointUsingReflection 激活增强方法!终于可以使用增强的方法了
return this.aspectJAdviceMethod.invoke(this.aspectInstanceFactory.getAspectInstance(), actualArgs);
}
catch (IllegalArgumentException ex) {
throw new AopInvocationException("Mismatch on arguments to advice method [" +
this.aspectJAdviceMethod + "]; pointcut expression [" +
this.pointcut.getPointcutExpression() + "]", ex);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
// invokeAdviceMethodWithGivenArgs方法中的aspectJAdviceMethod正是对于前置增强的方法,在这里得到了调用

第二个:AspectJAfterAdvice @After对应的增强器

后置增强与前置增强有少许不一致的地方之前讲解的前置增强,大致的结构是在拦截器中放置MethodBeforeAdviceInterceptor,而在MethodBeforeAdviceInterceptor中放置了
AspectJMethodBeforeAdvice,并在调用的invoke时首先串联调用,但是后置增强器却不一样,没有提供中间类,而是直接在拦截器中使用了中间的AspectJAfterAdvice
org.springframework.aop.aspectj包下AspectJAfterAdvice类

 public class AspectJAfterAdvice extends AbstractAspectJAdvice
implements MethodInterceptor, AfterAdvice, Serializable { public AspectJAfterAdvice(
Method aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) { super(aspectJBeforeAdviceMethod, pointcut, aif);
} @Override
public Object invoke(MethodInvocation mi) throws Throwable {
try {
return mi.proceed();
}
finally {
// 激活增强方法
invokeAdviceMethod(getJoinPointMatch(), null, null);
}
} @Override
public boolean isBeforeAdvice() {
return false;
} @Override
public boolean isAfterAdvice() {
return true;
} }

2、寻找匹配的增强器

前面的方法中已经完成了所有增强器的解析,但是对于所有的增强器来说,并不一定都适用于当前的bean,还要挑出适合的增强器,也就是满足我们配置中通配符的增强器
具体实现在下面的方法中 --> findAdvisorsThatCanApply()

org.springframework.aop.framework.autoproxy包下的AbstractAdvisorAutoProxyCreator类中

 protected List<Advisor> findAdvisorsThatCanApply(
List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) { ProxyCreationContext.setCurrentProxiedBeanName(beanName);
try {
// 过滤已经得到的advisors
return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
}
finally {
ProxyCreationContext.setCurrentProxiedBeanName(null);
}
}

看一下findAdvisorsThatCanApply()源码,如何过滤?
org.springframework.aop.support包下的AopUtils类中的findAdvisorsThatCanApply(List<Advisor>, Class<?>)方法

 public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
if (candidateAdvisors.isEmpty()) {
return candidateAdvisors;
}
List<Advisor> eligibleAdvisors = new ArrayList<>();
// 首先处理引介增强
for (Advisor candidate : candidateAdvisors) {
if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
eligibleAdvisors.add(candidate);
}
}
boolean hasIntroductions = !eligibleAdvisors.isEmpty();
for (Advisor candidate : candidateAdvisors) {
// 引介增强已经处理
if (candidate instanceof IntroductionAdvisor) {
// already processed
continue;
}
// 对于普通的bean的处理
if (canApply(candidate, clazz, hasIntroductions)) {
eligibleAdvisors.add(candidate);
}
}
return eligibleAdvisors;
}

findAdvisorsThatCanApply方法主要的功能是寻找所有增强器中适用于当前class的增强器。引介增强处理和普通的增强处理是不一样的,分开处理,真正的匹配逻辑是在
canApply()中的,看canApply的源码:

org.springframework.aop.support包下的AopUtils类中的canApply方法

 public static boolean canApply(Advisor advisor, Class<?> targetClass) {
return canApply(advisor, targetClass, false);
} public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
if (advisor instanceof IntroductionAdvisor) {
return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
}
else if (advisor instanceof PointcutAdvisor) {
PointcutAdvisor pca = (PointcutAdvisor) advisor;
return canApply(pca.getPointcut(), targetClass, hasIntroductions);
}
else {
// It doesn't have a pointcut so we assume it applies.
return true;
}
} public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {
Assert.notNull(pc, "Pointcut must not be null");
if (!pc.getClassFilter().matches(targetClass)) {
return false;
} MethodMatcher methodMatcher = pc.getMethodMatcher();
if (methodMatcher == MethodMatcher.TRUE) {
// No need to iterate the methods if we're matching any method anyway...
return true;
} IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
} Set<Class<?>> classes = new LinkedHashSet<>();
if (!Proxy.isProxyClass(targetClass)) {
classes.add(ClassUtils.getUserClass(targetClass));
}
classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); for (Class<?> clazz : classes) {
Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
for (Method method : methods) {
if (introductionAwareMethodMatcher != null ?
introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) :
methodMatcher.matches(method, targetClass)) {
return true;
}
}
}
return false;
}

最新文章

  1. 伪静态下Post无法响应的问题
  2. AngularJS-Uncaught Error: [$injector:modulerr]
  3. VS2012中使用纯C实现COM的小问题
  4. PHP 学习笔记 (二)
  5. Oracle (内连接)
  6. Java学习的随笔(一)对象概念、this指针、权限修饰符
  7. SPOJ 4110 Fast Maximum Flow (最大流模板)
  8. SMC MCU
  9. Jenkins + robot framework + git持续集成
  10. linux服务器上Apache配置多域名
  11. OpenCV——PS滤镜,渐变映射
  12. 【ShoppingWebCrawler】-基于Webkit内核的爬虫蜘蛛引擎概述
  13. 理解ClassLoader
  14. Java程序设计(第二版)复习 第二章
  15. python之设计模式
  16. SQL自动流水号函数
  17. 通过python的hashlib模块计算一个文件的MD5值
  18. JVM、Gc工作机制详解
  19. win10 Java环境变量,hadoop 环境变量
  20. (转)Springboot定时任务

热门文章

  1. Bootstrap——可拖动模态框(Model)
  2. 2019-8-31-dotnet-获取指定进程的输入命令行
  3. 建立 CRAMFS 包
  4. java 上传MultipartFile和String post请求
  5. 【数位DP】[LOJ10168] 恨7不成妻
  6. odoo 下 get_object_reference 函数
  7. leetcode-154-寻找旋转排序数组中的最小值
  8. 【JZOJ3347】树的难题
  9. go的单引号、双引号、反引号的区别
  10. VC操作Excel之基本操作(颜色等)【转载】