在Java中进行切面编程,通常需要借助Spring或AspectJ等第三方类库,而在scala中,通过巧妙的使用特征(trait)可以实现部分AOP的效果。比如我有这样一个操作:
trait Service{
def doAction(): Unit
}
我希望在doAction的之前和之后做一些额外的操作(比如记录日志,权限控制等),下面我定义了liang
trait BeforeServiceAspect extends Service{
abstract override def doAction(): Unit = {
println("before doAction ... " )
super.doAction();
}
}
trait AfterServiceAspect extends Service{
abstract override def doAction(): Unit = {
super.doAction();
println("after doAction ... ");
}
}
class ServiceImpl extends Service{
override def doAction(){
println("do job");
}
}
然后我们可以这样 实例化:
val s = new ServiceImpl with BeforeServiceAspect with AfterServiceAspect
你会发现当执行s.doAction的时候会打印出:
before doAction ...
do job
after doAction ...
这就是利用了trait的堆叠特性。