Resolving disambiguation in Autowiring DI pattern

Spring provides one more annotation, @Qualifier, to overcome the problem of disambiguation in autowiring DI. Let's see the following snippet of code with the @Qualifier annotation:

    @Service 
    public class TransferServiceImpl implements TransferService { 
    @Autowired 
    public TransferServiceImpl( @Qualifier("jdbcAccountRepository")
AccountRepository accountRepository) { ... }

Now I have wired the dependency by name rather than by type by using the @Qualifier annotation. So, Spring will search the bean dependency with the name "jdbcAccountRepository" for the TransferServiceImpl class. I have given the names of the beans as follows:

    @Repository("jdbcAccountRepository") 
    public class JdbcAccountRepository implements AccountRepository 
{..} @Repository("jpaAccountRepository") public class JpaAccountRepository implements AccountRepository {..}

@Qualifier, also available with the method injection and field injection component names, should not show implementation details unless there are two implementations of the same interface.

Let's now discuss some best practices to choose the DI pattern configuration for your Spring application.

Resolving dependency with Abstract Factory pattern

If you want to add the if...else conditional configuration for a bean, you can do so, and also add some custom logic if you are using Java configuration. But in the case of an XML configuration, it is not possible to add the if...then...else conditions. Spring provides the solution for conditions in an XML configuration by using the Abstract Factory Pattern. Use a factory to create the bean(s) you want, and use any complex Java code that you need in the factory's internal logic.

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

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