Monday, December 10, 2007

Groovy AOP - Part #4, Getter and Setter PCDs

I haven't implemented pointcut designators (PCDs) for getter and setter because I actually forgot about them.

I recall them this morning, and really see the advantage of using them for Grails domain classes. I think using it can definitely solve the problem's been caused by Hibernate setter issue. Here's the situation.

I have the domain class, User containing the password field passwd:

class User {
...
String passwd
}


What I wanted to do is to store MD5ed password by just calling new User(password:'abc').save(). But this won't work. It's the Hibernate limitation that does not allow me to have the setter for passwd, say setPasswd, because the setter will be called, at least, twice when Hibernate 1. initialises the object, 2. sets the value into the property. Yes, I got my password hashed twice !

So here can be a solution (I have to try it first to confirm this anyway).

Groovy AOP can provide a shortcut for getter and setter like:

class User {
static aspect = {
before(set:'passwd'){ value -> value = MD5(value) }
}
...
String passwd

}



Why this's going to work? I think it works because Groovy AOP works at meta-layer, while Hibernate works at bytecode (proxied) layer. It's possible for Hibernate to set the property directly (as it does not invoke the call through Groovy invoker). Good use case?

No comments: