Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How it work the Spring @Autowired annotation on a constructor?

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

like image 782
AndreaNobili Avatar asked Sep 14 '25 21:09

AndreaNobili


1 Answers

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 when TransferServiceImpl is constructed.

3- There are more than one bean with the type AccountRepository:

  • Fallback to the bean name. In this case, Spring will look for a bean of type AccountRepository with name repo. If a match is found, it will be injected.
  • The name fallback fails (multiple beans with the same type and name). An exception will be thrown.
like image 87
Khalid Avatar answered Sep 17 '25 11:09

Khalid