I am studying Spring framework and I have the following doubt related the @Autowired annotation on the constructor of this example:
@Component
public class TransferServiceImpl implements TransferService {
@Autowired
public TransferServiceImpl(AccountRepository repo) {
this.accountRepository = repo;
}
}
So what exactly mean? That the AccountRepository repo object (definied as a component somewhere) is automatically injected into the TransferServiceImpl() constructor?
How it work this operation? Is it done by type? (because AccountRepository is a singleton for Spring default), or what?
Tnx
Spring will look for the
AccountRepository
bean in the container. There are multiple possible scenarios:1- There are zero beans with the type
AccountRepository
. An exception will be thrown.2- There is one bean with the type
AccountRepository
. The bean will be injected whenTransferServiceImpl
is constructed.3- There are more than one bean with the type
AccountRepository
:AccountRepository
with namerepo
. If a match is found, it will be injected.