Enforce Required Dependencies in Spring 2.0

Posted on July 10, 2007 by Scott Leberknight

Spring 2.0 added the @Required annotation that allows you to define which bean properties are required to be injected. In combination with the RequiredAnnotationBeanPostProcessor, Spring will blow up at application startup if any dependencies are not satisfied. In my (admittedly limited) testing of this feature, only one unsatisfied dependency is reported at a time - in other words Spring fails fast at the first missing dependency. In any case, the following is all you need to do to enable this feature.

First, annotate the setter methods for required properties.

// In some class that requires a UserDao to be injected.
@Required
public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
}

Second, in one of your Spring application context files, add the following:

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>

That's it. If you want you can configure the RequiredAnnotationBeanPostProcessor to look for a different type of annotation, for example maybe you want your own @Injected annotation:

// In some class that requires a UserDao to be injected.
@Injected
public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
}
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor">
    <property name="requiredAnnotationType" value="com.acme.annotation.Injected"/>
<bean>

Overall this is a nice feature that might save you some time debugging a missing dependency and at the same time making your code a little more explicit, since the annotated setter methods tell the reader something, i.e. that this is a "special" property that is required to be set before the class can successfully be used.



Post a Comment:
Comments are closed for this entry.