Spring之面向切面编程AOP
Sring为我们提供了面向切面的编程方式,简称AOP。
先从理论出发,走进AOP的世界。
AOP:面向切面编程,相对于OOP面向对象编程。
Spring的AOP的存在的目的是为了解耦。AOP可以让一组类共享相同的行为。在OOP中只能通过继承类和实现接口,来使代码的耦合度增强,且类继承只能单继承,阻碍更多行为添加到一组类上,AOP弥补了OOP的不足。
Spring支持AspectJ的注解式切面编程。
(1)试用@Aspect声明是一个切面。
(2)使用@After、@Before、@Around定义建言(advice),可直接将拦截规则(切点)作为参数。
(3)其中@After、@Before、@Around参数的拦截规则为切点(PointCut),为了是切点复用,可使用@PointCut专门定义拦截规则,然后再@After、@Before、@Around的参数中调用。
(4)其中符合条件的每一个被拦截处为连接点(JoinPoint)。
示例将演示基于注解拦截和基于方法规则拦截两种方式,演示一种模拟记录操作的日志系统的实现。其中注解式拦截能够很好地控制要拦截的粒度和获得更丰富的信息,Spring本身在事务处理(@Transcational)和数据缓存(@Cacheable等)上面都使用此种形式的拦截。
在我们的项目中,消息通知机制采用了AOP切面编程。
首先需要在Spring的配置文件中增加以下配置:
<aop:config> <aop:pointcut expression="execution(* com.jty.service.*.*(..)) or execution(* com.jty.*.service.*.*(..))" id="txPoint"/> <!--com.jty.service.*.*(..)表达式可以根据需要修改--> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/> </aop:config> <context:annotation-config/> <aop:aspectj-autoproxy/> <aop:config> <aop:aspect id="message" ref="messageAspect"> <aop:pointcut id="send" expression="execution(* com.jty.service.impl.*.*(..)) and @annotation(com.jty.message.mailcomponent.annotation.SendMessage) or execution(* com.jty.*.service.impl.*.*(..)) and @annotation(com.jty.message.mailcomponent.annotation.SendMessage))"/> <aop:around pointcut-ref="send" method="doProcessMessage"/> </aop:aspect> <aop:aspect id="replaceAspect" ref="imageAspect"> <aop:pointcut id="replaceImage" expression="execution(* com.jty.service.impl.*.*(..)) and @annotation(com.jty.image.annotation.ReplaceImage) or execution(* com.jty.*.service.impl.*.*(..)) and @annotation(com.jty.image.annotation.ReplaceImage))"/> <aop:before pointcut-ref="replaceImage" method="doReplaceImage"/> </aop:aspect> </aop:config>
首先从Spring的核心概念对此配置文件进行解读:
AOP核心概念
1、横切关注点
对哪些方法进行拦截,拦截后怎么处理,这些关注点称之为横切关注点
2、切面(aspect)
类是对物体特征的抽象,切面就是对横切关注点的抽象
3、连接点(joinpoint)
被拦截到的点,因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截到的方法,实际上连接点还可以是字段或者构造器
4、切入点(pointcut)
对连接点进行拦截的定义
5、通知(advice)
所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类
6、目标对象
代理的目标对象
7、织入(weave)
将切面应用到目标对象并导致代理对象创建的过程
8、引入(introduction)
在不修改代码的前提下,引入可以在运行期为类动态地添加一些方法或字段

浙公网安备 33010602011771号