Java 它是如何在构造函数上运行Spring@Autowired注释的?
我正在研究Spring框架,我对本例构造函数的@Autowired注释有以下疑问:Java 它是如何在构造函数上运行Spring@Autowired注释的?,java,spring,frameworks,annotations,spring-annotations,Java,Spring,Frameworks,Annotations,Spring Annotations,我正在研究Spring框架,我对本例构造函数的@Autowired注释有以下疑问: @Component public class TransferServiceImpl implements TransferService { @Autowired public TransferServiceImpl(AccountRepository repo) { this.accountRepository = repo; } } 那到底是什么意思?Accou
@Component
public class TransferServiceImpl implements TransferService {
@Autowired
public TransferServiceImpl(AccountRepository repo) {
this.accountRepository = repo;
}
}
那到底是什么意思?AccountRepository repo对象(定义为某个地方的组件)是否自动注入TransferServiceImpl()构造函数
它是如何运作的?是按类型做的吗?(因为AccountRepository是Spring默认的单例存储库),还是什么
Tnx使用
@Component
告诉扫描进程该类是一个bean,使用@autowire
告诉后处理器在spring存储库中搜索AccountRepository
类型的bean。如果找到bean,它将与带注释的构造函数一起使用。根据作用域,将使用一个新实例(prototype
),或者将传递一个已经实例化的bean(singleton
)。无论如何,如果有两个bean与构造函数参数匹配,将抛出异常。使用@Component
告诉扫描进程该类是一个bean,使用@autowire
告诉后处理器在spring存储库中搜索AccountRepository
类型的bean。如果找到bean,它将与带注释的构造函数一起使用。根据作用域,将使用一个新实例(prototype
),或者将传递一个已经实例化的bean(singleton
)。如果无论如何有两个bean与构造函数参数匹配,将抛出异常。Spring将在容器中查找AccountRepository
bean。有多种可能的情况:
1-类型为AccountRepository
的bean为零。将引发异常
2-有一个bean的类型为AccountRepository
。当构建TransferServiceImpl
时,将注入bean
3-有多个bean的类型为AccountRepository
:
- 回退到bean名称。在本例中,Spring将查找名为
的repo
类型的bean。如果找到匹配项,将对其进行注入AccountRepository
- 名称回退失败(具有相同类型和名称的多个bean)。将引发异常
- Spring将在容器中查找
AccountRepository
bean。有多种可能的情况:
1-类型为AccountRepository
的bean为零。将引发异常
2-有一个bean的类型为AccountRepository
。当构建TransferServiceImpl
时,将注入bean
3-有多个bean的类型为AccountRepository
:
- 回退到bean名称。在本例中,Spring将查找名为
的repo
类型的bean。如果找到匹配项,将对其进行注入AccountRepository
- 名称回退失败(具有相同类型和名称的多个bean)。将引发异常