Injecting Spring beans

In the preceding code, I declared the beans TransferService, AccountRepository, and TransferRepository; these beans had no dependencies. But, actually, the TransferService bean depends on AccountRepository and TransferRepository. Let's see the following changes made in the AppConfig class to declare the beans:

    package com.packt.patterninspring.chapter4.bankapp.config; 
    import org.springframework.context.annotation.Bean; 
    import org.springframework.context.annotation.Configuration; 
    @Configuration 
    public class AppConfig { 
      @Bean 
      public TransferService transferService(){ 
        return new TransferServiceImpl(accountRepository(), 
transferRepository()); } @Bean public AccountRepository accountRepository() { return new JdbcAccountRepository(); } @Bean public TransferRepository transferRepository() { return new JdbcTransferRepository(); } }

In the preceding example, the simplest way to wire up beans in a Java-based configuration is to refer to the referenced bean's method. The transferService() method constructs the instance of the TransferServiceImpl class by calling the arguments constructor that takes AccountRepository and TransferRepository. Here, it seems that the constructor of the TransferServiceImpl class is calling the accountRepository() and transferRepository() methods to create instances of AccountRepository and TransferRepository respectively, but it is not an actual call to create instances. The Spring container creates instances of AccountRepository and TransferRepository, because the accountRepository() and transferRepository() methods are annotated with the @Bean annotation. Any call to the bean method by another bean method will be intercepted by Spring to ensure the default singleton scope (this will be discussed further in Chapter 5, Understanding the Bean Life cycle and Used Patterns) of the Spring beans by that method is returned rather than allowing it to be invoked again.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset