Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended usage of Spring's @Required annotation

Tags:

java

spring

I see that Spring has a @Required annotation to mark member variables in beans that must be set.

Is there a best practice for using this?

For instance, might it be better to set these values in the constructor and make these parameters explicitly required (esp. when used outside of Spring)?

Thanks!

like image 230
Vinnie Avatar asked May 05 '09 13:05

Vinnie


People also ask

What is @required annotation used for?

The @Required annotation applies to bean property setter methods and it indicates that the affected bean property must be populated in XML configuration file at configuration time. Otherwise, the container throws a BeanInitializationException exception.

What is the use of @required annotation in spring boot?

The @Required annotation in spring is a method-level annotation used in the setter method of a bean property and therefore making the setter-injection compulsory.

Why do we use @repository annotation?

Spring @Repository annotation is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects.


1 Answers

While not referring to the @Required annotation directly, Martin Fowler provides this advice...

He prefers to set object values in the constructor rather than in setters as it will "give you a clear statement of what it means to create a valid object in an obvious place" while it also "allows you to clearly hide any fields that are immutable by simply not providing a setter".

like image 110
Vinnie Avatar answered Sep 22 '22 22:09

Vinnie