Commit 473c54d9 by SunWei峰

aop源码探索初步完成,暂停学习,先找工作,拿到offer再继续学习

parent 13d47b00
......@@ -131,6 +131,7 @@ public abstract class AbstractAspectJAdvisorFactory implements AspectJAdvisorFac
@SuppressWarnings("unchecked")
@Nullable
protected static AspectJAnnotation<?> findAspectJAnnotationOnMethod(Method method) {
// 获取指定方法上的注解并使用 AspectJAnnotation 封装
for (Class<?> clazz : ASPECTJ_ANNOTATION_CLASSES) {
AspectJAnnotation<?> foundAnnotation = findAnnotation(method, (Class<Annotation>) clazz);
if (foundAnnotation != null) {
......
......@@ -84,14 +84,18 @@ public class BeanFactoryAspectJAdvisorsBuilder {
List<String> aspectNames = this.aspectBeanNames;
if (aspectNames == null) {
// 如果为空表示尚未缓存,进行缓存解析。这里用了DLC 方式来进行判断
synchronized (this) {
aspectNames = this.aspectBeanNames;
if (aspectNames == null) {
List<Advisor> advisors = new ArrayList<>();
aspectNames = new ArrayList<>();
// 1. 获取所有的beanName。从容器中获取所有的BeanName
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Object.class, true, false);
// 遍历beanName, 找出对应的增强方法
for (String beanName : beanNames) {
// 不合法的bean略过,由子类定义规则,默认true
if (!isEligibleBean(beanName)) {
continue;
}
......@@ -101,12 +105,16 @@ public class BeanFactoryAspectJAdvisorsBuilder {
if (beanType == null) {
continue;
}
// 2. 如果bean 被 @AspectJ 注解修饰 且不是 Ajc 编译, 则进一步处理
if (this.advisorFactory.isAspect(beanType)) {
// 添加到缓存中
aspectNames.add(beanName);
// 封装成AspectMetadata
AspectMetadata amd = new AspectMetadata(beanType, beanName);
if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
MetadataAwareAspectInstanceFactory factory =
new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
// 3. 解析标记AspectJ注解中的增强方法,也就是被 @Before、@Around 等注解修饰的方法,并将其封装成 Advisor
List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);
if (this.beanFactory.isSingleton(beanName)) {
this.advisorsCache.put(beanName, classAdvisors);
......@@ -114,10 +122,12 @@ public class BeanFactoryAspectJAdvisorsBuilder {
else {
this.aspectFactoryCache.put(beanName, factory);
}
// 保存 Advisor
advisors.addAll(classAdvisors);
}
else {
// Per target or per this.
// 如果当前Bean是单例,但是 Aspect 不是单例则抛出异常
if (this.beanFactory.isSingleton(beanName)) {
throw new IllegalArgumentException("Bean with name '" + beanName +
"' is a singleton, but aspect instantiation model is not singleton");
......@@ -138,6 +148,7 @@ public class BeanFactoryAspectJAdvisorsBuilder {
if (aspectNames.isEmpty()) {
return Collections.emptyList();
}
// 4. 将所有的增强方法保存到缓存中。
List<Advisor> advisors = new ArrayList<>();
for (String aspectName : aspectNames) {
List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName);
......
......@@ -94,6 +94,7 @@ final class InstantiationModelAwarePointcutAdvisorImpl
this.declarationOrder = declarationOrder;
this.aspectName = aspectName;
// 懒加载实例
if (aspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
// Static part of the pointcut is a lazy type.
Pointcut preInstantiationPointcut = Pointcuts.union(
......@@ -110,6 +111,7 @@ final class InstantiationModelAwarePointcutAdvisorImpl
// A singleton aspect.
this.pointcut = this.declaredPointcut;
this.lazy = false;
// 将增强封装为 Advice
this.instantiatedAdvice = instantiateAdvice(this.declaredPointcut);
}
}
......
......@@ -122,16 +122,21 @@ public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto
@Override
public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {
// 获取标记为 AspectJ 的类
Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
// 获取标记为 AspectJ 的名字
String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();
// 进行合法性验证
validate(aspectClass);
// We need to wrap the MetadataAwareAspectInstanceFactory with a decorator
// so that it will only instantiate once.
// 这里需要 MetadataAwareAspectInstanceFactory ,所以这里初始化了一次
MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =
new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);
List<Advisor> advisors = new ArrayList<>();
// getAdvisorMethods(aspectClass) 获取 aspectClass 中没有被 @PointCut 注解修饰的方法
for (Method method : getAdvisorMethods(aspectClass)) {
// Prior to Spring Framework 5.2.7, advisors.size() was supplied as the declarationOrderInAspect
// to getAdvisor(...) to represent the "current position" in the declared methods list.
......@@ -141,6 +146,7 @@ public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto
// discovered via reflection in order to support reliable advice ordering across JVM launches.
// Specifically, a value of 0 aligns with the default value used in
// AspectJPrecedenceComparator.getAspectDeclarationOrder(Advisor).
// 将方法封装成 Advisor 。如果找不到@PointCut 的信息,则会返回 null。
Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, 0, aspectName);
if (advisor != null) {
advisors.add(advisor);
......@@ -148,12 +154,14 @@ public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto
}
// 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.
// 获取 DeclaredParents 注解并处理。@DeclaredParents 注解可以实现指定某些代理类是某些接口的实现。
for (Field field : aspectClass.getDeclaredFields()) {
Advisor advisor = getDeclareParentsAdvisor(field);
if (advisor != null) {
......@@ -202,28 +210,41 @@ public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto
public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory,
int declarationOrderInAspect, String aspectName) {
// 又进行一次合法性校验
validate(aspectInstanceFactory.getAspectMetadata().getAspectClass());
// 1. 切点信息的获取。这里如果没有被 Aspect 系列注解(Pointcut、Around、Before等)修饰会返回null
AspectJExpressionPointcut expressionPointcut = getPointcut(
candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());
// 如果获取不到相关信息直接返回null
if (expressionPointcut == null) {
return null;
}
// 2. 根据切点信息封装成增强器
return new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod,
this, aspectInstanceFactory, declarationOrderInAspect, aspectName);
}
@Nullable
private AspectJExpressionPointcut getPointcut(Method candidateAdviceMethod, Class<?> candidateAspectClass) {
// 获取方法上的注解,包括 Pointcut.class, Around.class, Before.class, After.class,
// AfterReturning.class, AfterThrowing.class
AspectJAnnotation<?> aspectJAnnotation =
AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);
if (aspectJAnnotation == null) {
return null;
}
// 到这里必然有 AspectJ系列的注解了
// 使用 AspectJExpressionPointcut 实例封装获取的信息
AspectJExpressionPointcut ajexp =
new AspectJExpressionPointcut(candidateAspectClass, new String[0], new Class<?>[0]);
// 提取出的得到的注解中的表达式
// 如 @Pointcut("execution(* com.kingfish.aopdemo.controller.AopController.hello(String))") 中的
// execution(* com.kingfish.aopdemo.controller.AopController.hello(String))
// 对于 @Before("pointCut()") 获取的则是 pointCut()
ajexp.setExpression(aspectJAnnotation.getPointcutExpression());
if (this.beanFactory != null) {
ajexp.setBeanFactory(this.beanFactory);
......@@ -260,6 +281,7 @@ public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto
AbstractAspectJAdvice springAdvice;
// 根据不同的注解生成不同的通知(增强)
switch (aspectJAnnotation.getAnnotationType()) {
case AtPointcut -> {
if (logger.isDebugEnabled()) {
......
......@@ -103,6 +103,7 @@ public abstract class AopConfigUtils {
public static void forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistry registry) {
if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
// 设置 proxyTargetClass 属性
definition.getPropertyValues().add("proxyTargetClass", Boolean.TRUE);
}
}
......@@ -110,6 +111,7 @@ public abstract class AopConfigUtils {
public static void forceAutoProxyCreatorToExposeProxy(BeanDefinitionRegistry registry) {
if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
// 添加 exposeProxy 属性
definition.getPropertyValues().add("exposeProxy", Boolean.TRUE);
}
}
......@@ -120,18 +122,23 @@ public abstract class AopConfigUtils {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
// 如果有注册,则判断优先级,将优先级的高的保存
// 如果已经存在了自动代理创建器,且存在的自动代理创建器与现在的并不一致,那么需要根据优先级来判断到底要使用哪个
if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
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最重要的就是改变所对应的className 属性
apcDefinition.setBeanClassName(cls.getName());
}
}
// 如果已经存在自动代理创建器,并且与将要创建的一致,那么无需再次创建
return null;
}
// 没有发现,开始创建
RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
beanDefinition.setSource(source);
beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
......
......@@ -71,21 +71,33 @@ public abstract class AopNamespaceUtils {
registerComponentIfNecessary(beanDefinition, parserContext);
}
/**
* 注册 AnnotationAwareAspectJAutoProxyCreator
*
* @param parserContext
* @param sourceElement
*/
public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary(
ParserContext parserContext, Element sourceElement) {
// 注册或升级 AutoProxyCreator定义 beanName 为 org.springframework.aop.config.
// internalAutoProxyCreator 的 BeanDefinition
BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(
parserContext.getRegistry(), parserContext.extractSource(sourceElement));
// 对于 Proxy-target-class 以及 expose-proxy 属性的处理
useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement);
// 注册组件通知,便于监听器做进一步处理
// 其中 beanDefinition 的 className 为 AnnotationAwareAspectJAutoProxyCreator
registerComponentIfNecessary(beanDefinition, parserContext);
}
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);
......
......@@ -38,12 +38,15 @@ import org.springframework.lang.Nullable;
*/
class AspectJAutoProxyBeanDefinitionParser implements BeanDefinitionParser {
// TODO: 2022/8/17 AOP开始解析
// TODO: 2022/8/17 AOP解析
@Override
@Nullable
public BeanDefinition parse(Element element, ParserContext parserContext) {
// 注册annotationAwareAspectJAutoProxyCreator
AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);
// 注解中子类的处理
extendBeanDefinition(element, parserContext);
// Spring Aop 构建在动态代理之上,因此 Spring 对Aop的支持局限于方法拦截。
return null;
}
......
......@@ -54,6 +54,9 @@ public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
// 如果目标对象实现了接口,默认会采用JDK动态代理实现AOP
// 如果目标对象实现了接口,可以强制使用CGLIB动态代理实现AOP
// 如果目标对象没有实现接口,必须采用CGLIB代理
if (!NativeDetector.inNativeImage() &&
(config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config))) {
Class<?> targetClass = config.getTargetClass();
......
......@@ -160,22 +160,27 @@ final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializa
Object oldProxy = null;
boolean setProxyContext = false;
// 获取目标源
TargetSource targetSource = this.advised.targetSource;
Object target = null;
try {
// equals 方法的处理
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
// hash 方法的处理
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
// 处理 DecoratingProxy 类
else if (method.getDeclaringClass() == DecoratingProxy.class) {
// There is only getDecoratedClass() declared -> dispatch to proxy config.
return AopProxyUtils.ultimateTargetClass(this.advised);
}
// 处理 Class类的isAssignableFrom(Class cls) 方法
else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
// Service invocations on ProxyConfig with the proxy config...
......@@ -183,7 +188,7 @@ final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializa
}
Object retVal;
// 是否暴露代理对象。有时候目标对象内部的自我调用将无法实施切面中的增强,则需要通过此属性暴露
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
......@@ -196,6 +201,8 @@ final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializa
Class<?> targetClass = (target != null ? target.getClass() : null);
// Get the interception chain for this method.
// 获取当前方法的拦截链路,其中包括将AspectJMethodBeforeAdvice、AspectJAfterAdvice、AspectJAfterReturningAdvice
// 转换成合适的类型(InterceptorAndDynamicMethodMatcher)
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
// Check whether we have any advice. If we don't, we can fallback on direct
......@@ -204,18 +211,23 @@ final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializa
// We can skip creating a MethodInvocation: just invoke the target directly
// Note that the final invoker must be an InvokerInterceptor so we know it does
// nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
// 拦截链路为空则直接调用切点方法
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
// We need to create a method invocation...
// 否则构建一个新的 方法调用对象 ReflectiveMethodInvocation
// 以便于使用proceed 方法进行链接表用拦截器
MethodInvocation invocation =
new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
// Proceed to the joinpoint through the interceptor chain.
// 调用方法,执行拦截器链路
retVal = invocation.proceed();
}
// Massage return value if necessary.
// 返回结果
Class<?> returnType = method.getReturnType();
if (retVal != null && retVal == target &&
returnType != Object.class && returnType.isInstance(proxy) &&
......
......@@ -159,15 +159,18 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea
@Nullable
public Object proceed() throws Throwable {
// We start with an index of -1 and increment early.
// 执行完所有增强后执行切点方法
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}
// 获取下一个要执行的拦截器
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher dm) {
// Evaluate dynamic method matcher here: static part will already have
// been evaluated and found to match.
// 动态匹配
Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
return dm.interceptor.invoke(this);
......@@ -175,12 +178,14 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea
else {
// Dynamic matching failed.
// Skip this interceptor and invoke the next in the chain.
// 不匹配则使用拦截器
return proceed();
}
}
else {
// It's an interceptor, so we just invoke it: The pointcut will have
// been evaluated statically before this object was constructed.
// 普通拦截器,直接调用拦截器
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
......
......@@ -55,16 +55,20 @@ public class DefaultAdvisorAdapterRegistry implements AdvisorAdapterRegistry, Se
@Override
public Advisor wrap(Object adviceObject) throws UnknownAdviceTypeException {
// 针对本身就是 Advisor 的,无需处理
if (adviceObject instanceof Advisor) {
return (Advisor) adviceObject;
}
// 不是 advisor 或者 advice 类型,抛异常
if (!(adviceObject instanceof Advice advice)) {
throw new UnknownAdviceTypeException(adviceObject);
}
// MethodInterceptor 使用 DefaultPointcutAdvisor 封装
if (advice instanceof MethodInterceptor) {
// So well-known it doesn't even need an adapter.
return new DefaultPointcutAdvisor(advice);
}
// 存在 Advisor 适配器,也要进行进行封装
for (AdvisorAdapter adapter : this.adapters) {
// Check that it is supported.
if (adapter.supportsAdvice(advice)) {
......
......@@ -74,7 +74,7 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC
@Nullable
protected Object[] getAdvicesAndAdvisorsForBean(
Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
// 获取增强方法
List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
if (advisors.isEmpty()) {
return DO_NOT_PROXY;
......@@ -93,8 +93,12 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC
* @see #extendAdvisors
*/
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
// 获取所有的增强
List<Advisor> candidateAdvisors = findCandidateAdvisors();
// 寻找增强中适用于bean的增强并应用
// 搜索给定的候选增强以查找可以应用于指定 bean 的所有增强。
List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
// 在链表首部,添加增强链增强
extendAdvisors(eligibleAdvisors);
if (!eligibleAdvisors.isEmpty()) {
eligibleAdvisors = sortAdvisors(eligibleAdvisors);
......@@ -123,8 +127,10 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC
protected List<Advisor> findAdvisorsThatCanApply(
List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
// 设置标记位
ProxyCreationContext.setCurrentProxiedBeanName(beanName);
try {
// 过滤增强器 例如不满足表达式等
return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
}
finally {
......
......@@ -280,6 +280,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
return pvs; // skip postProcessPropertyValues
}
// TODO: 2022/8/17 创建AOP代理
/**
* Create a proxy with the configured interceptors if the bean is
* identified as one to proxy by the subclass.
......@@ -288,8 +289,10 @@ public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
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);
}
}
......@@ -326,21 +329,27 @@ public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
* @return a proxy wrapping the bean, or the raw bean instance as-is
*/
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是否代表一个基础设施类,基础设施类不应代理,或者配置了指定的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());
......@@ -441,19 +450,24 @@ public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
}
ProxyFactory proxyFactory = new ProxyFactory();
// 获取当前类中属性
proxyFactory.copyFrom(this);
// 决定对于给定的 bean 是否应该使用 targetClass 属性 而不是他的代理接口
// 检查 ProxyTargetClass 设置以及 preserveTargetClass
if (proxyFactory.isProxyTargetClass()) {
// Explicit handling of JDK proxy targets and lambdas (for introduction advice scenarios)
if (Proxy.isProxyClass(beanClass) || ClassUtils.isLambdaClass(beanClass)) {
// Must allow for introductions; can't just set interfaces to the proxy's interfaces only.
for (Class<?> ifc : beanClass.getInterfaces()) {
// 添加代理接口
proxyFactory.addInterface(ifc);
}
}
}
else {
// No proxyTargetClass flag enforced, let's apply our default checks...
// 目标类代理
if (shouldProxyTargetClass(beanClass, beanName)) {
proxyFactory.setProxyTargetClass(true);
}
......@@ -463,10 +477,15 @@ public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
}
Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
// 加入增强器
proxyFactory.addAdvisors(advisors);
// 设置要代理的类
proxyFactory.setTargetSource(targetSource);
// 定制代理
customizeProxyFactory(proxyFactory);
// 用来控制代理工厂被配置之后,是否还允许修改通知
// 缺省值为false(在代理配置后,不允许修改代理的配置)
proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
......@@ -518,10 +537,12 @@ public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
*/
protected Advisor[] buildAdvisors(@Nullable String beanName, @Nullable Object[] specificInterceptors) {
// Handle prototypes correctly...
// 解析所有注册的 interceptorName
Advisor[] commonInterceptors = resolveInterceptorNames();
List<Object> allInterceptors = new ArrayList<>();
if (specificInterceptors != null) {
// 加入拦截器
if (specificInterceptors.length > 0) {
// specificInterceptors may equal PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS
allInterceptors.addAll(Arrays.asList(specificInterceptors));
......@@ -543,6 +564,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
}
Advisor[] advisors = new Advisor[allInterceptors.size()];
// 拦截器进行封装转化为 Advisor
for (int i = 0; i < allInterceptors.size(); i++) {
advisors[i] = this.advisorAdapterRegistry.wrap(allInterceptors.get(i));
}
......
......@@ -70,6 +70,7 @@ public class BeanFactoryAdvisorRetrievalHelper {
if (advisorNames == null) {
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the auto-proxy creator apply to them!
// 获取所有类为 Advisor 的 beanName
advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Advisor.class, true, false);
this.cachedAdvisorBeanNames = advisorNames;
......@@ -78,14 +79,17 @@ public class BeanFactoryAdvisorRetrievalHelper {
return new ArrayList<>();
}
// 遍历所有的beanName找到对应的增强方法
List<Advisor> advisors = new ArrayList<>();
for (String name : advisorNames) {
// 合法情况
if (isEligibleBean(name)) {
if (this.beanFactory.isCurrentlyInCreation(name)) {
if (logger.isTraceEnabled()) {
logger.trace("Skipping currently created advisor '" + name + "'");
}
}
// bf创建完成
else {
try {
advisors.add(this.beanFactory.getBean(name, Advisor.class));
......
......@@ -306,6 +306,7 @@ public abstract class AopUtils {
return candidateAdvisors;
}
List<Advisor> eligibleAdvisors = new ArrayList<>();
// 处理引介增强
for (Advisor candidate : candidateAdvisors) {
if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
eligibleAdvisors.add(candidate);
......@@ -313,10 +314,12 @@ public abstract class AopUtils {
}
boolean hasIntroductions = !eligibleAdvisors.isEmpty();
for (Advisor candidate : candidateAdvisors) {
// 引介增强已创建完毕
if (candidate instanceof IntroductionAdvisor) {
// already processed
continue;
}
// 普通Bean处理
if (canApply(candidate, clazz, hasIntroductions)) {
eligibleAdvisors.add(candidate);
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment