Recently I’ve been heads down writing a Grails Solr plugin for using Solr to index and search Grails domain objects, content and other documents. I share more on that in the next several day and weeks. While doing so I implement annotations for the first time. In this example, I create an annotation type that lets you annotate a class property to specify a custom Solr index field name. In usage it looks like this:
import org.grails.plugins.solr.Solr
class aDomain {
@Solr(field="thedomainstitle")
String title
}
The imported class above is actually an interface that defines the annotation:
package org.grails.plugins.solr
import java.lang.annotation.*
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Solr {
String field();
}
This is fairly self explanatory. The name of the annotation is “Solr” and there is one propery field with a value of String. Almost identical to the java equivalent.
Now to access the annotation value for the field, you simply need the get a reference to the annotation and call the method on it defined above: field(). So with a bit of context below, I define an indexSolr() method for each domain class, loop through each property and check if there is an annotation of Solr defined for the field, if so I set the value of field() to the docKey which is used as the Solr field name for the property.
application.domainClasses.each { dc ->
dc.metaClass.indexSolr < < { ->
//.......
application.getArtefact(DomainClassArtefactHandler.TYPE, delegate.class.name).getProperties().each {
//.......
def theField = delegate.class.declaredFields.find{ field -> field.name == it.name}
if(theField.isAnnotationPresent(Solr)) {
docKey = theField.getAnnotation(Solr).field()
}
//........
}
//........
}
}
Powerful, yet simple.





