The @Primary annotation

By default, in Spring Framework, DI is done by type, which means that when there are multiple dependencies with the same type, the NoUniqueBeanDefinitionException exception will be thrown. It indicates that the Spring container is unable to select a bean for DI because of more than one eligible candidate. In that case, we can use the @Primary annotation and take control of the selection process. Let's see the following code:

public interface CustomerService {  
public void customerService();
}

@Component
public class AccountService implements CustomerService {
....
}
@Component
@Primary
public class BankingService implements CustomerService {
....
}

In the case of the previous example, there are two customer services available: BankingService and AccountService. Due to the @Primary annotation, components can only use BankingService to wire dependencies on CustomerService.

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

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