Step 1: Declare the module that represents the basic action method taction
Declares a module that represents a basic action method tactiontrait taction {def doAction}
Step 2: Define a feature that adds pre-processing and post-processing features Tbeforeafter
Trait Tbeforeafter extends Taction {abstract override def doAction { //doaction pre-processing println ("/entry Before-action ") super.doaction //doaction post-processing println ("/exit after-action ") }}
Override the virtual method by using the abstract override def doAction {} statement above. Specifically, the super.doaction is the key, and he calls the Taction Doaction method. The principle is that because doaction is a virtual method, it is actually executed by the method defined in the called entity class. 、
Step 3: Implement the entity classes that are actually executed realaction
Class Realaction extends Taction { def doAction = { println ("* * Real action done!! **") }}
Test
Object Testtrait { def main (args:array[string]): Unit = {
Val Act1 = new realaction with Tbeforeafter
Act1.doaction
Val act2 = new realaction with Tbeforeafter with Ttwiceaction
Act2.doaction
Val act3 = new realaction with ttwiceaction with Tbeforeafter
Act3.doaction
}}
/entry before-action
* * Real Action done!! **
/exit after-action
Then define other aspects for him, and then add those aspects to the same object's methods. Then define an aspect that will execute the source method two times.
Trait Ttwiceaction extends Taction { abstract override def doAction {for (I <-1 to 2) { super.doaction
println ("==>no." + i)}}
Below, Tbeforeafter and ttwiceaction are mixed together to execute.
/entry before-action
* * Real Action done!! **
/exit after-action
==>no. 1
/entry before-action
* * Real Action done!! **
/exit after-action
==>no. 2
Along with the original method of the Before/after actions were executed two times each. Then try again by reversing the mix order.
/entry before-action
* * Real Action done!! **
==>no. 1
* * Real Action done!! **
==>no. 2
/exit after-action
After this execution, the original implementation method was executed two times, but the Before/after was executed only once in the whole loop. This is done according to the order defined by the WITH statement, and there is nothing strange about this principle. The order in which Scala features are so mixed is the same as the ASPECTJ aspect and the interceptor of spring.
Scala-trait Implementing AOP Programming