Building Microservices with Spring
上QQ阅读APP看书,第一时间看更新

Annotating beans for autowiring

Spring provides support for automatic bean wiring. This means that Spring automatically resolves the dependencies that are required by the dependent bean by finding other collaborating beans in the application context. Bean Autowiring is another way of DI pattern configuration. It reduces verbosity in the application, but the configuration is spread throughout the application. Spring's @Autowired annotation is used for auto bean wiring. This @Autowired annotation indicates that autowiring should be performed for this bean.

In our example, we have TransferService which has dependencies of AccountRepository and TransferRepository. Its constructor is annotated with @Autowired indicating that when Spring creates the TransferService bean, it should instantiate that bean by using its annotated constructor, and pass in two other beans, AccountRepository and TransferRepository, which are dependencies of the TransferService bean. Let's see the following code:

    package com.packt.patterninspring.chapter4.bankapp.service; 
    import org.springframework.beans.factory.annotation.Autowired; 
    import org.springframework.stereotype.Service; 
    import com.packt.patterninspring.chapter4.bankapp.model.Account; 
    import com.packt.patterninspring.chapter4.bankapp.model.Amount; 
    import com.packt.patterninspring.chapter4.bankapp.
repository.AccountRepository; importcom.packt.patterninspring.chapter4.
bankapp.repository.TransferRepository; @Service public class TransferServiceImpl implements TransferService { AccountRepository accountRepository; TransferRepository transferRepository; @Autowired public TransferServiceImpl(AccountRepository accountRepository,
TransferRepository transferRepository) { super(); this.accountRepository = accountRepository; this.transferRepository = transferRepository; } @Override public void transferAmmount(Long a, Long b, Amount amount) { Account accountA = accountRepository.findByAccountId(a); Account accountB = accountRepository.findByAccountId(b); transferRepository.transfer(accountA, accountB, amount); } }
Note--As of Spring 4.3, the @Autowired annotation is no more required if you define only one construct with arguments in that class. If class has multiple argument constructors, then you have to use the @Autowired annotation on any one of them.

The @Autowired annotation is not limited to the construction; it can be used with the setter method, and can also be used directly in the field, that is, an autowired class property directly. Let's see the following line of code for setter and field injection.