Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Spring’s @Required Annotation

DZone's Guide to

Using Spring’s @Required Annotation

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

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.

 

From http://www.captaindebug.com/2011/09/using-springs-required-annotation.html

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}