Using @Autowired with the fields

Here you can annotate those class properties which are required for this class to achieve a business goal. Let's see the following code:

    public class TransferServiceImpl implements TransferService { 
      @Autowired 
      AccountRepository accountRepository; 
      @Autowired 
      TransferRepository transferRepository; 
      //... 
    } 

In the preceding code, the @Autowired annotation resolves the dependency by type and then by name if the property name is the same as the bean name in the Spring container. By default, the @Autowired dependency is a required dependency--it raises an exception if the dependency is not resolved, it doesn't matter whether we have used it with a constructor or with the setter method. You can override the required behavior of the @Autowired annotation by using the required attribute of this annotation. You can set this attribute with the Boolean value false as follows:

    @Autowired(required = false) 
    public void setAccountRepository(AccountRepository
accountRepository) { this.accountRepository = accountRepository; }

In the preceding code, we have set the required attribute with the Boolean value false. In this case, Spring will attempt to perform autowiring, but if there are no matching beans, it will leave the bean unwired. But as a best practice of code, you should avoid setting its value as false until it is absolutely necessary.

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

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