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

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}