AOP

关于AOP的个人理解

AOP联盟定义的AOP体系结构把与AOP相关的概念大致分为了由高到低、从使用到实现的三个层次。关于这个体系结构,个人的理解是这样的,从上往下,最高层是语言和开发环境,在这个环境中可以看到几个重要的概念:base可以视为待增强对象,或者说目标对象;aspect指切面,通常包含对于base的增强应用;configuration可以看成是一种编织或者说配置,通过在AOP体系中提供这个configuration配置环境,可以把base和aspect结合起来,从而完成切面对目标对象的编织实现。

对Spring平台或者说生态系统来说,AOP是Spring框架的核心功能模块之一。AOP与IOC容器的结合使用, 为应用开发或者Spring自身功能的扩展都提供了许多便利。Spring AOP的实现和其他特性的实现一样,非常丰富,除了可以使用Spring本身提供的AOP实现之外,还封装了业界优秀的AOP解决方案AspectJ来让应用使用。在这里,主要对Spring自身的AOP实现原理做一些解析;在这个AOP实现中,Spring充分利用了IOC容器Proxy代理对象以及AOP拦截器的功能特性,通过这些对AOP基本功能的封装机制,为用户提供了AOP的实现框架。所以,要了解这些AOP的基本实现,需要我们对Java 的Proxy机制有一些基本了解。

AOP实现的基本线索

AOP实现中,可以看到三个主要的步骤,一个是代理对象的生成,然后是拦截器的作用,然后是Aspect编织的实现。AOP框架的丰富,很大程度体现在这三个具体实现中,所具有的丰富的技术选择,以及如何实现与IOC容器的无缝结合。毕竟这也是一个非常核心的模块,需要满足不同的应用需求带来的解决方案需求。
在Spring AOP的实现原理中,我们主要举ProxyFactoryBean的实现作为例子和实现的基本线索进行分析;很大一个原因,是因为ProxyFactoryBean是在Spring IoC环境中,创建AOP应用的最底层方法,从中,可以看到一条实现AOP的基本线索。在ProxyFactoryBean中,它的AOP实现需要依赖JDK或者CGLIB提供的Proxy特性。从FactoryBean中获取对象,是从getObject()方法作为入口完成的。然后为proxy代理对象配置advisor链,这个配置是在initializeAdvisorChain方法中完成的;然后就为生成AOP代理对象做好了准备,生成代理对象如下所示:


Java代码
1.private synchronized Object getSingletonInstance() {
2. if (this.singletonInstance == null) {
3. this.targetSource = freshTargetSource();
4. if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
5. // Rely on AOP infrastructure to tell us what interfaces to proxy.
6. Class targetClass = getTargetClass();
7. if (targetClass == null) {
8. throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");
9. }
10. // 这里设置代理对象的接口 setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
11. }
12. // Initialize the shared singleton instance.
13. super.setFrozen(this.freezeProxy);
14. // 注意这里的方法会使用ProxyFactory来生成我们需要的Proxy
15. this.singletonInstance = getProxy(createAopProxy());
16. }
17. return this.singletonInstance;
18.}
19.//使用createAopProxy返回的AopProxy来得到代理对象
20.protected Object getProxy(AopProxy aopProxy) {
21. return aopProxy.getProxy(this.proxyClassLoader);
22.}
private synchronized Object getSingletonInstance() {
if (this.singletonInstance == null) {
this.targetSource = freshTargetSource();
if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
// Rely on AOP infrastructure to tell us what interfaces to proxy.
Class targetClass = getTargetClass();
if (targetClass == null) {
throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");
}
// 这里设置代理对象的接口 setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
}
// Initialize the shared singleton instance.
super.setFrozen(this.freezeProxy);
// 注意这里的方法会使用ProxyFactory来生成我们需要的Proxy
this.singletonInstance = getProxy(createAopProxy());
}
return this.singletonInstance;
}
//使用createAopProxy返回的AopProxy来得到代理对象
protected Object getProxy(AopProxy aopProxy) {
return aopProxy.getProxy(this.proxyClassLoader);
}


上面我们看到了在Spring中通过ProxyFactoryBean实现AOP功能的第一步,得到AopProxy代理对象的基本过程,下面我们看看AopProxy代理对象的拦截机制是怎样发挥作用,是怎样实现AOP功能的。我们知道,对代理对象的生成,有CGLIB和JDK两种生成方式,在CGLIB中,对拦截器设计是通过在Cglib2AopProxy的AopProxy代理对象生成的时候,在回调DynamicAdvisedInterceptor对象中实现的,这个回调的实现在intercept方法中完成。对于AOP是怎样完成对目标对象的增强的,这些实现是封装在AOP拦截器链中,由一个个具体的拦截器来完成的。具体拦截器的运行是在以下的代码实现中完成的,这些调用在ReflectiveMethodInvocation中。

Java代码 
1.public Object proceed() throws Throwable {
2. // We start with an index of -1 and increment early.
3. //如果拦截器链中的拦截器迭代调用完毕,这里开始调用target的函数,这个函数是通过反射机制完成的,具体实现在:AopUtils.invokeJoinpointUsingReflection方法里面。
4. if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
5. return invokeJoinpoint();
6. }
7. //这里沿着定义好的 interceptorOrInterceptionAdvice链进行处理。
8. Object interceptorOrInterceptionAdvice =
9. this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
10. if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
11. // Evaluate dynamic method matcher here: static part will already have
12. // been evaluated and found to match.
13. //这里对拦截器进行动态匹配的的判断,还记得我们前面分析的pointcut吗?这里是触发进行匹配的地方,如果和定义的pointcut匹配,那么这个advice将会得到执行。
14. InterceptorAndDynamicMethodMatcher dm =
15. (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
16. if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
17. return dm.interceptor.invoke(this);
18. }
19. else {
20. // Dynamic matching failed.
21. // Skip this interceptor and invoke the next in the chain.
22. // //如果不匹配,那么这个proceed会被递归调用,直到所有的拦截器都被运行过为止。
23. return proceed();
24. }
25. }
26. else {
27. // It's an interceptor, so we just invoke it: The pointcut will have
28. // been evaluated statically before this object was constructed.
29. //如果是一个interceptor,直接调用这个interceptor对应的方法
30. return((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
31. }
32.}
public Object proceed() throws Throwable {
// We start with an index of -1 and increment early.
//如果拦截器链中的拦截器迭代调用完毕,这里开始调用target的函数,这个函数是通过反射机制完成的,具体实现在:AopUtils.invokeJoinpointUsingReflection方法里面。
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}
//这里沿着定义好的 interceptorOrInterceptionAdvice链进行处理。
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
// Evaluate dynamic method matcher here: static part will already have
// been evaluated and found to match.
//这里对拦截器进行动态匹配的的判断,还记得我们前面分析的pointcut吗?这里是触发进行匹配的地方,如果和定义的pointcut匹配,那么这个advice将会得到执行。
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
return dm.interceptor.invoke(this);
}
else {
// Dynamic matching failed.
// Skip this interceptor and invoke the next in the chain.
// //如果不匹配,那么这个proceed会被递归调用,直到所有的拦截器都被运行过为止。
return proceed();
}
}
else {
// It's an interceptor, so we just invoke it: The pointcut will have
// been evaluated statically before this object was constructed.
//如果是一个interceptor,直接调用这个interceptor对应的方法
return((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}


在调用拦截器的时候,我们接下去就可以看到对advice的通知的调用。而经过一系列的注册,适配的过程以后,拦截器在拦截的时候,会调用到预置好的一个通知适配器,设置通知拦截器,这是一系列Spring设计好为通知服务的类的一个,是最终完成通知拦截和实现的地方,非常的关键。比如,对MethodBeforeAdviceInterceptor的实现是这样的:

Java代码
1.public class MethodBeforeAdviceInterceptor implements MethodInterceptor, Serializable {   
2.
3. private MethodBeforeAdvice advice;
4.
5.
6. /**
7. * Create a new MethodBeforeAdviceInterceptor for the given advice.
8. * @param advice the MethodBeforeAdvice to wrap
9. */
10. public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
11. Assert.notNull(advice, "Advice must not be null");
12. this.advice = advice;
13. }
14. //这个invoke方法是拦截器的回调方法,会在代理对象的方法被调用的时候触发回调。
15. public Object invoke(MethodInvocation mi) throws Throwable {
16. this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
17. return mi.proceed();
18. }
19.}
public class MethodBeforeAdviceInterceptor implements MethodInterceptor, Serializable {

private 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;
}
//这个invoke方法是拦截器的回调方法,会在代理对象的方法被调用的时候触发回调。
public Object invoke(MethodInvocation mi) throws Throwable {
this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
return mi.proceed();
}
}


在代码中,可以看到,就是这里,会调用advice的before方法!这样就成功的完成了before通知的编织!

因为Spring AOP本身并不打算成为一个一统天下的AOP框架,秉持Spring的一贯设计理念,设想中的Spring设计目标应该是,致力于AOP框架与IOC容器的紧密集成,通过集成AOP技术为JavaEE应用开发中遇到的普遍问题提供解决方案,从而为AOP用户使用AOP技术提供最大的便利,从这个角度上为Java EE的应用开发人员服务。在没有使用第三方AOP解决方案的时候,Spring通过虚拟机的Proxy特性和CGLIB实现了AOP的基本功能,我想,如果有了Spring AOP实现原理的知识背景,再加上我们对源代码实现的认真解读,可以为我们了解其他AOP框架与IOC容器的集成原理,也打下了很好的基础,并真正了解一个AOP框架是在怎样实现的。

这还真是就是我们喜欢开源软件一个原因,有了源代码,软件就没有什么神秘的面纱了!本立而道生,多读源代码吧,或者找一本从源代码出发讲解软件实现的书来看看,就像以前我们学习操作系统,学习TCP/IP那样!一定会有长进的。
### AOP 概念及核心思想 Aspect-Oriented Programming (AOP) 是一种编程范式,旨在将横切关注点(cross-cutting concerns)从核心业务逻辑中分离出来[^1]。这些横切关注点通常包括日志记录、性能统计、事务管理、安全性检查等,它们会影响多个模块或类的功能,但在传统的面向对象编程中往往被分散地插入到业务代码中,导致代码重复和难以维护。AOP 提供了一种机制,允许开发者把这些横切关注点集中定义为独立的模块,称为“切面”(Aspect)。 #### 核心概念 以下是 AOP 的几个关键术语: - **切面(Aspect)**:切面是横切关注点的模块化实现,通常由通知(Advice)和切入点(Pointcut)组成。 - **通知(Advice)**:定义了切面在何时执行以及执行的具体行为。常见的通知类型包括 `Before`(方法执行前)、`After`(方法执行后)、`Around`(环绕方法执行)等。 - **切入点(Pointcut)**:定义了切面在哪些连接点(Join Point)上生效。连接点通常是方法调用或异常抛出的位置。 - **连接点(Join Point)**:程序执行过程中的特定点,例如方法调用或对象实例化。 - **目标对象(Target Object)**:被切面所影响的对象。 - **代理对象(Proxy)**:通过 AOP 动态创建的对象,用于拦截对目标对象的调用并应用切面逻辑。 ### AOP 的实现方式 AOP 可以通过静态织入(Static Weaving)或动态代理(Dynamic Proxy)来实现。静态织入通常在编译时完成,而动态代理则在运行时生成代理对象[^2]。Spring AOP 使用动态代理技术,在运行时为需要增强的目标对象创建代理对象,并在代理对象上调用方法时插入切面逻辑。 #### Spring AOP 的使用方法 以下是一个基于 Spring AOP 的简单示例,展示如何定义切面和应用通知: ```java import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class LoggingAspect { // 定义切入点,匹配所有以 "execute" 开头的方法 @Before("execution(* com.example.service.*.execute*(..))") public void logBeforeMethod() { System.out.println("Logging before method execution"); } } ``` 在这个例子中: - `@Aspect` 注解标识这是一个切面类。 - `@Before` 注解定义了一个前置通知,表示在指定的切入点之前执行。 - 切入点表达式 `execution(* com.example.service.*.execute*(..))` 表示匹配 `com.example.service` 包下所有以 `execute` 开头的方法。 ### 优势与应用场景 AOP 的主要优势在于能够降低代码耦合度,提高代码的可维护性和可扩展性[^3]。它适用于以下场景: - **日志记录**:在方法执行前后记录日志信息。 - **性能监控**:统计方法的执行时间或资源消耗。 - **事务管理**:统一管理事务的开启、提交和回滚。 - **安全性检查**:验证用户权限或限制访问。 - **异常处理**:集中捕获和处理异常。 ### 注意事项 虽然 AOP 提供了强大的功能,但也需要注意以下几点: - 过度使用 AOP 可能会导致代码难以调试,因为切面逻辑可能隐藏在业务代码之外。 - 切入点表达式的复杂性可能增加维护难度。 - 动态代理可能会引入一定的性能开销,尤其是在高频调用的场景下。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值