Junior — Middle
Is the use of the @Autowired annotation mandatory to indicate that a dependency should be injected?
sobes.tech AI
Answer from AI
Using the @Autowired annotation in Spring is not the only way to indicate that a dependency should be injected. It is used for automatic wiring of components by type.
However, starting with Spring Framework 4.3, if a class has a single constructor, the @Autowired annotation on it can be omitted — Spring will automatically inject dependencies through that constructor.
Other ways to inject dependencies include:
- Through XML configuration
- Using the
@Injectannotation (JSR-330) - Through explicit bean creation and dependency passing
Thus, @Autowired is convenient and often used, but not mandatory in all cases.