I got the same question as in In Groovy Is there a way to decorate every class to add tracing? but this answer is now several years old, so i wanted to know if there now is any better and more easy way to execute some code before, after or around the execution of methods. I would prefer something with annotations like

@TraceLog
class Foo {
   def bar() {
       println "in bar"
   }
}

or

class Foo { 
   @TraceLog
   def bar() {
       println "in bar"
   }
}

So that when i call bar(), some code (defined by TraceLog Aspect or similiar) is executed before "in bar" is printed. Is that possible with groovy yet?

有帮助吗?

解决方案

You can do this via an AST transformation, as shown here

Care should be taken with that example however as the endMessage is just added as the last statement in the method. If the method has a return value, this is likely to be wrong...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top