Monday, July 10, 2006

Pointcuts, even more fun with regex!

Ok, so maybe 'fun' isn't the right word, but I have to say that I though it was pretty damn cool the first time I swapped out a pointcut for a regex one (yesterday)! Incase you're already wondering what the heck I'm blabbering on about, currently ColdSpring has a pretty simplistic pointcut model, you can only really define them as globs, strings which can contain the '*' wild-card. Simple, yes, but in that simplicity lies tremendous power, which is what I find so fascinating about AOP in the first places. So currently we can match all the set or get methods in an object by defining a pointcut with the mappedName 'set*' or 'get*', and just for a refresher, we would do that by creating an advisor like so (here we are providing a cachingAdvice):

<bean id="cachingAdvisor"
    class="coldspring.aop.support.NamedMethodPointcutAdvisor">
    <property name="advice">
      <ref bean="cachingAdvice" />
    </property>
    <property name="mappedNames">
      <value>get*,set*
    </property>
</bean>


Here we are defining a NamedMethodPointcutAdvisor and providing it a list for mapped names, get* and set*. Side note, the <list> element in ColdSpring refers to a CF Array, following the Java DTD, to use a CF List provide a string list as a <value>. Behind the scenes, ColdSpring will create a NamedMethodPointcut, and provide it with the mappedNames value. This pointcut is what the framework will use to preform the method matching in order to identify the methods that you would like to add, in this case, the cachingAdvice to. So this is all very good, but what if what we want to do is add caching to all the methods EXCEPT the getters and setters. Ahhh, enter the RegexMethodPointcutAdvisor, which as you would probably guess, will create a RegexMethodPointcut. So lets see how that will look, with a pretty complex regex pattern to match all methods except the setters:

<bean id="cachingAdvisor"
    class="coldspring.aop.support.RegexMethodPointcutAdvisor">
    <property name="advice">
      <ref bean="catalogCachingAdvice" />
    </property>
    <property name="pattern">
      <value>^((?!get).)*$
    </property>
</bean>


So as you can see, we are defining a very similar advisor, but this time we provide a property called 'pattern' which will be our regex pattern. This one's a bit complex as we need to use negative back referencing, which honestly is a bit confusing to me, but google is your friend! But the great part is now we can define methods to exclude from matching, which is tremendously powerful. Want to look for getters and setters? Use this pattern ^((?![g|s]et).)*$ and you should be fine.

The two new components, RegexMethodPointcutAdvisor and RegexMethodPointcut are available via cvs. Happy AOP'n!

0 Comments:

Post a Comment

<< Home