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

3.6k Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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.
0
On

With @Component you tell the scan process that this class is a bean, with @autowire you tell the post processor to search through the spring repository for a bean of type AccountRepository. If the bean is found, it will be used with the annotated constructor. Based on the scope, a new instance will be used (prototype) or an already instanciated bean will be passed (singleton). If in anyway there are two beans matching the constructor argument, an exception will be thrown.