Java Reference
In-Depth Information
@Before("execution(void set*(*))")
void reportOnSet(JoinPoint jp) {
String method = jp.signature.name
String base = method - 'set'
String property = base[0].toLowerCase() + base[1..-1]
def current = jp.target."$property"
log.info "About to change $property from $current to ${jp.args[0]}"
}
}
The UpdateReporter class is written in Groovy. It has the @Aspect and @Before
annotationsexactlyastheJavaaspectdid.Themethodbeinginvokediscomputedthesame
way the Java aspect did, with the only minor difference being that Groovy accesses the
signature and name propertiesratherthanexplicitlyinvokingtheassociated getSig-
nature and getName methods. That's a case of foreshadowing, actually, because it
means that all I really need to do is to figure out the name of the property.
The property is found by taking the name of the set method, subtracting out the letters
set , and converting the result to standard property syntax. Now that I have the name of
the property, I just need to access it from the target, which is done on the next line. I used
a Groovy string to make sure that the property is evaluated. The result is that in three lines
of Groovy I now know what the original value of the property is. All that remains is to log
it to standard output.
To run this aspect I just added a corresponding bean to the configuration file:
<bean id= "updater" class= "mjg.aspects.UpdateReporter" />
Now if I run the same test case the output is as shown here:
INFO: About to change one from 1 to one
INFO: setOne about to change to one on POJO [one=1, two=2, three=3.0]
INFO: About to change two from 2 to 22
INFO: setTwo about to change to 22 on POJO [one=one, two=2, three=3.0]
INFO: About to change three from 3.0 to 333.0
INFO: setThree about to change to 333.0 on POJO [one=one, two=22, three=3.0]
BoththeGroovyaspectandtheJavaaspectareexecutingonthe set methodsofthePOJO.
The advantage of the Groovy aspect is that it's easily able to determine the existing value
of the property before changing it.
Search WWH ::




Custom Search