Tuesday, 6 September 2011

Using Spring’s @Required Annotation

When your application needs a bean class, it’s not unusual for certain attributes to be mandatory, which if missed from your Spring config file will cause you problems at some undetermined future time. The Guys at Spring thought of this and came up with the @Required annotation that you can apply to your bean’s setter method:

  // Snippet from a plain old bean...
 
private int id;
 
private String street1;

 
@Required
 
public void setId(int id) {
   
this.id = id;
 
}

 
@Required
 
public void setStreet1(String street1) {
   
this.street1 = street1;
 
}

...together with the following addition to your Spring configuration file:

<!-- Switch on the required annotation  -->
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>

...which gets Spring to check at load time that your Setter method has been called and throwing a org.springframework.beans.factory.BeanInitializationException if you forget setup your bean correctly.

I personally prefer to use constructor args to initialize beans with mandatory parameters, providing that there aren’t too many of them. There are at least two benefits here: firstly you don’t need to mess around with @Required annotations because if you have a missing constructor argument you’ll know about it and secondly, initializing beans using constructor args means that its attributes can be marked as final, which improves thread safety.

There is one proviso here. Using constructor args is only okay if your bean is not being used by some API that expects your bean to have Setter methods. In this case you’ve no choice and @Required is a good idea.

No comments: