上QQ阅读APP看书,第一时间看更新
The Autowiring DI pattern and disambiguation
The @Autowiring annotation reduces verbosity in the code, but it may create some problems when two of the same type of beans exist in the container. Let's see what happens in that situation, with the following example:
@Service public class TransferServiceImpl implements TransferService { @Autowired public TransferServiceImpl(AccountRepository accountRepository) {
... } }
The preceding snippet of code shows that the TransferServiceImpl class has a dependency with a bean of type AccountRepository, but the Spring container contains two beans of the same type, that is, the following:
@Repository public class JdbcAccountRepository implements AccountRepository
{..} @Repository public class JpaAccountRepository implements AccountRepository {..}
As seen from the preceding code, there are two implementations of the AccountRepository interface--one is JdbcAccountRepository and another is JpaAccountRepository. In this case, the Spring container will throw the following exception at startup time of the application:
At startup: NoSuchBeanDefinitionException, no unique bean of type [AccountRepository] is defined: expected single bean but found 2...