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