Spring / Spring7 basics Interview questions
What is the purpose of the @Autowired annotation?
@Autowired tells the Spring container to automatically resolve and inject a matching bean into a constructor, setter, or field. Spring first tries to match by type; if more than one bean of that type exists, it falls back to matching by the parameter or field name, or you can disambiguate with @Qualifier.
@Component public class ReportService { private final EmailSender sender; @Autowired public ReportService(EmailSender sender) { this.sender = sender; } }
On a single-constructor class, @Autowired is actually optional since Spring 4.3 - the container uses that constructor implicitly. It's still commonly written for clarity, and remains required when a class defines multiple constructors.
More Related questions...