因为工作用不到,好久没有关注spring了.周末看了下spring aop,感觉还不错.
假定想通过aop实现transaction,一些核心得概念如下:
target object, //业务对象
||
||-------->//这个过程叫
weaving,spring框架在运行时完成的
||
//
AOP proxy, //具备事务特性的业务对象
假定某个业务对象,比如提款机好了,叫 com.jh.Teller,它有一个方法叫transfer
class Teller {
boolean transfer(Accout from, Accout to, double howmuch) {
withdraw(from, howmuch);
deposit(to, howmuch);
}
}
如何让"
transfer"这个方法在一个"
事务中"执行呢?
这里就引出三个概念:
transfer ->
Joinpoint(
pointcut可以看作是一个用来匹配joinpoint的正则表达式,
比如get*()会匹配getName())
事务 ->
Aspect
用spring来实现这个aspect大概就是如下这个样子
public class TransactionAspect { void beforeBusiness() { //open transaction... } void afterBusiness() { //commit transaction... } void afterExcetion() { //rollback transaction }}
像事务管理这类玩意,他们在每一个业务的前,后执行.
重复,但是又没办法使用OO的方法把这种重复去掉.这就是crosscutting concern的意思
把如上像beforeBusiness(),afterBusiness() 这类在aspect里定义的方法叫做
advice,
用来指定当一个joinpoint出现时应该采取的行动.
综合上面的, 在spring的配置文件里一个基于描述性的事务看起来应该是如下样子:
<aop:config> <aop:aspect id="transactionAspect" ref="transactionAspectBean"> <aop:pointcut id="transactionalMethod" expression="execution(* com.jh.*Service.*(..))"/> <aop:before pointcut-ref="transactionalMethod" method="beforeBusiness"/> <aop:after pointcut-ref="transactionalMethod" method="afterBusiness"/> <aop:after-exception pointcut-ref="transactionalMethod" method="afterException"/> </aop:aspect></aop:config>
大致是这个样子,具体参考spring的手册.
到这里为止spring aop里面的一些概念就都在了.