Over a million developers have joined DZone.

Using Spring’s @Required Annotation

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

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

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

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

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

{{ parent.tldr }}

{{ parent.urlSource.name }}