1. 概念
Aspect-Oriented Programming (AOP)可以說是OOP(Object Oriented Programming换吧,面向?qū)ο缶幊?的補(bǔ)充和完善折晦。
OOP引入封裝、繼承沾瓦、多態(tài)等概念來建立一種對象層次結(jié)構(gòu)满着,用于模擬公共行為的一個(gè)集合。不過OOP允許開發(fā)者定義縱向的關(guān)系贯莺,但并不適合定義橫向的關(guān)系风喇,例如日志功能。
AOP技術(shù)恰恰相反缕探,它利用一種稱為"橫切"的技術(shù)魂莫,剖解開封裝的對象內(nèi)部,并將那些影響了多個(gè)類的公共行為封裝到一個(gè)可重用模塊爹耗,并將其命名為"Aspect"耙考,即切面。
2. AOP核心概念
- Aspect(切面)
- Join point
- Advice
- Pointcut
- Introduction
- Target object
- AOP proxy
- Weaving
3. Spring對AOP的支持
3.1示例
<!--AOP begin-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean id="testAspect" class="com.xxxx.fabu.aspect.TestAspect"/>
<!--要求進(jìn)入到AOP的配置潭兽,重點(diǎn)配置切入點(diǎn)倦始,以及確定切入的處理操作方法-->
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.xxxx.fabu.service..*.*(..)) and args(id)"/>
<aop:aspect ref="testAspect"><!--進(jìn)行切面的配置,如果是切面控制應(yīng)該有一個(gè)控制的類-->
<aop:before method="beforeMethod" pointcut-ref="pointCut" arg-names="id"/>
<aop:after method="afterMethod" pointcut="execution(* com.xxxx.fabu.service..*.*(..))"/>
</aop:aspect>
</aop:config>
<!--AOP end-->
3.2 其他示例
- the execution of any public method:
execution(public * *(..))
- the execution of any method with a name beginning with "set":
execution(* set*(..))
- the execution of any method defined by the AccountService interface:
execution(* com.xyz.service.AccountService.*(..))
- the execution of any method defined in the service package:
execution(* com.xyz.service.*.*(..))
- the execution of any method defined in the service package or a sub-package:
execution(* com.xyz.service..*.*(..))
- any join point (method execution only in Spring AOP) within the service package:
within(com.xyz.service.*)
- any join point (method execution only in Spring AOP) within the service package or a sub-package:
within(com.xyz.service..*)
- any join point (method execution only in Spring AOP) where the proxy implements the AccountService interface:
this(com.xyz.service.AccountService)