Saturday, February 20, 2010

POGO + Singleton + Mixin

Something worth sharing (or probably you may suggest me with a better solution) about injection/Mixin on Groovy's object that is being a singleton.

Let's start off with an example. I have a Users class with a private singleton, e.g.
@Mixin(Whatever)
class Users{

  private static Users instance = new Users()

  def doGetUserByEmail(){}

  static def getUserByEmail(){
    instance.doGetUserByEmail()
  }
}

Unfortunately, this is not working as Users.instance is constructed within the class before Groovy does more thing with its interpreter (at this point, I still have limited knowledge about Groovy, but that's the basic idea).

So I let Groovy to handle the construction of the singleton for me, with @Singleton - resulted with the same effect.

However, @Singleton(lazy = true) solves the problem, as the late/lazy instantiation happens on a "ready" POGO class.

1 comment:

Anonymous said...

+1, I found this out myself after much hair pulling. Glad to see I'm not just insane.