balteo
balteo

Reputation: 24679

What could cause a dependency not to be set in Spring

I came across Spring's @Required annotation and I am not sure when to use it.

My main interrogation is: What could cause a Spring dependency not to be set thereby justifying the use of @Required?

Upvotes: 1

Views: 85

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340783

First check out 4.9.1 @Required in reference documentation. IMHO The usage of this annotation is limited these days when autowiring is so commonly used.

It was quite nice in the XML days - if you forgot to define <property name="movieFinder" .../> in XML but remembered to put @Required around movieFinder field or setter, Spring would throw an exception.

Note that this annotation won't save you from the most common Spring-novice error - creating a bean manually using new operator, outside of container control. Spring has to post-process the bean and throws exception only when the annotated class was actually created by the container (but the dependency was not injexted).

These days you just annotate that field with @Autowired/@Resource/@Inject and if bean is not found (otherwise leaving null) exception is thrown (no such bean or similar). If you can put @Required annotation, what is preventing you from replacing it with @Autowired and getting rid of XML altogether?

That being said, for some @Required might have a nice documentation value.

Upvotes: 2

smp7d
smp7d

Reputation: 5032

It is to prevent developer error for the most part.

Sometimes developers think that something will be on the context that is not actually there for a plethora of reasons, including:

  1. Simply forgot to add the bean
  2. Dependency issue (when components from dependencies are autodetected)
  3. Type/Package misunderstanding

In these cases it is nicer to fail on context load instead of something like an NPE later.

Upvotes: 1

Related Questions