继续源码学习,看了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;
}

spring源码学习之AOP(一)的更多相关文章

  1. spring源码学习之AOP(二)

    接着上一篇中的内容! 3.创建代理 在获取了所有的bean对应的增强器之后,便可以进行代理的创建了org.springframework.aop.framework.autoproxy包下的Abstr ...

  2. spring源码学习之路---深入AOP(终)

    作者:zuoxiaolong8810(左潇龙),转载请注明出处,特别说明:本博文来自博主原博客,为保证新博客中博文的完整性,特复制到此留存,如需转载请注明新博客地址即可. 上一章和各位一起看了一下sp ...

  3. Spring 源码学习——Aop

    Spring 源码学习--Aop 什么是 AOP 以下是百度百科的解释:AOP 为 Aspect Oriented Programming 的缩写,意为:面向切面编程通过预编译的方式和运行期动态代理实 ...

  4. Spring 源码学习笔记10——Spring AOP

    Spring 源码学习笔记10--Spring AOP 参考书籍<Spring技术内幕>Spring AOP的实现章节 书有点老,但是里面一些概念还是总结比较到位 源码基于Spring-a ...

  5. spring源码学习之路---IOC初探(二)

    作者:zuoxiaolong8810(左潇龙),转载请注明出处,特别说明:本博文来自博主原博客,为保证新博客中博文的完整性,特复制到此留存,如需转载请注明新博客地址即可. 上一章当中我没有提及具体的搭 ...

  6. Spring源码学习

    Spring源码学习--ClassPathXmlApplicationContext(一) spring源码学习--FileSystemXmlApplicationContext(二) spring源 ...

  7. Spring源码学习-容器BeanFactory(一) BeanDefinition的创建-解析资源文件

    写在前面 从大四实习至今已一年有余,作为一个程序员,一直没有用心去记录自己工作中遇到的问题,甚是惭愧,打算从今日起开始养成写博客的习惯.作为一名java开发人员,Spring是永远绕不过的话题,它的设 ...

  8. 【目录】Spring 源码学习

    [目录]Spring 源码学习 jwfy 关注 2018.01.31 19:57* 字数 896 阅读 152评论 0喜欢 9 用来记录自己学习spring源码的一些心得和体会以及相关功能的实现原理, ...

  9. Spring 源码学习笔记11——Spring事务

    Spring 源码学习笔记11--Spring事务 Spring事务是基于Spring Aop的扩展 AOP的知识参见<Spring 源码学习笔记10--Spring AOP> 图片参考了 ...

随机推荐

  1. OA系统和ERP系统的区别

    一.OA和ERP的区别 1.含义不同: OA指Office Automation,中文简称自动办公系统,帮助企业内部管理沟通的工具,比如新闻公告.内部沟通.考勤.办公.员工请假.审批流程等. ERP指 ...

  2. Python全栈开发:Ajax全套

    概述 对于WEB应用程序:用户浏览器发送请求,服务器接收并处理请求,然后返回结果,往往返回就是字符串(HTML),浏览器将字符串(HTML)渲染并显示浏览器上. 1.传统的Web应用 一个简单操作需要 ...

  3. signed main()

    主函数由int main()改成signed main() 好处:把int改成long long 的时候不用单独把它改成int了,懂的人都懂(滑稽

  4. Nginx在windows系统的常用命令

    启动 start nginx 强制停止 nginx.exe -s stop 重启 nginx.exe -s reload

  5. 开发函数计算的正确姿势 —— 使用 ROS 进行资源编排

    前言 首先介绍下在本文出现的几个比较重要的概念: 函数计算(Function Compute): 函数计算是一个事件驱动的服务,通过函数计算,用户无需管理服务器等运行情况,只需编写代码并上传.函数计算 ...

  6. ng-zorro-mobile中遇到的问题

    一.Modal(弹出框)使用上的问题 在官方文档中,Modal是这样使用的: 这里需要注意的一点就是,看到上方代码中只用了Modal的全局方式,所以个人认为下面这段注入初始化的东西是没有用的便去掉: ...

  7. centos7 搭建 php7 + nginx (2)

    安装php php下载地址 # 避免出错,先安装下面 yum install libzip libzip-devel libxml2-devel openssl openssl-devel bzip2 ...

  8. PHPstorm同步服务器代码的缺点---命名空间undefined

      在把一个服务器的代码同步到phpstorm下开发的时候,发现新建的命名空间代码都失效了,然而换到 https://blog.csdn.net/afraid_to_have/article/deta ...

  9. 菜鸟nginx源码剖析数据结构篇(七) 哈希表 ngx_hash_t(下)[转]

    菜鸟nginx源码剖析数据结构篇(七) 哈希表 ngx_hash_t(下) Author:Echo Chen(陈斌) Email:chenb19870707@gmail.com Blog:Blog.c ...

  10. opencv-图像类型、深度、通道

    转自:图像类型   与  opencv中图像基础(大小,深度,通道) 一.图像基本类型 在计算机中,按照颜色和灰度的多少可以将图像分为四种基本类型. 1. 二值图像 2. 灰度图像 3. 索引图像 4 ...