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!
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.
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.
Spring @Repository annotation is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With