You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@velocity.apache.org by James Talmage <ja...@jrtechnical.com> on 2010/11/02 18:58:49 UTC
Declarative Dependency Injection via Comments
Intellij Idea will let you define the class type of context elements in a
multi-line comments like this:
#* @vtlvariable name="service"
type="com.google.appengine.api.users.UserService" *#
this provides very handy code completion, but I thought it would be cool to
let that same line of code double as a way to grab objects from my
dependency injection framework.
I have modified the velocity 1.6.4 code base to find "Annotations" and
"Attributes" in multi-line comments, and provide hooks for processing them.
The following line:
#* @inject @vtlvariable name="service"
type="com.google.appengine.api.users.UserService" *#
Would produce a callback containing two annotations (@inject &
@vtlvariable), and two attributes (name & type). It's then pretty straight
forward to create code that will do something with those values (in my case
- grab the specified type from a google guice context, and put it in the
context using the specified name).
I could see other uses for it: Instantiating tools objects, ensuring the
context contains a specific type (@typesafe), require that a context has a
certain value (@required).
It was a fun weekend project that I'd be happy to donate back to the
community, if there is interest.