And*_*ili 1 java spring frameworks annotations spring-annotations
我正在研究Spring框架,我对此示例的构造函数的@Autowired注释有以下疑问:
@Component
public class TransferServiceImpl implements TransferService {
@Autowired
public TransferServiceImpl(AccountRepository repo) {
this.accountRepository = repo;
}
}
Run Code Online (Sandbox Code Playgroud)
究竟是什么意思呢?该AccountRepository回购对象(definied作为组分某处)自动注射到 TransferServiceImpl()构造?
它是如何运作的?是按类型完成的吗?(因为AccountRepository是Spring默认的单例),还是什么?
TNX
Spring将AccountRepository在容器中查找bean.有多种可能的情况:
1-类型为零豆AccountRepository.将抛出异常.
2-有一种类型的豆AccountRepository.TransferServiceImpl构建时将注入bean .
3-有多种类型的bean AccountRepository:
AccountRepository名称类型的bean repo.如果找到匹配,则会注入.你告诉@Component扫描进程这个类是一个 bean,@autowire你告诉后处理器在 spring 存储库中搜索类型为 的 bean AccountRepository。如果找到该 bean,它将与带注释的构造函数一起使用。根据范围,将使用新实例 ( prototype) 或传递已实例化的 bean ( singleton)。如果无论如何有两个 bean 与构造函数参数匹配,则会抛出异常。