[英]Spring: Two beans implementing one interface with one as @Primary - autowiring creates both beans
One Interface: BeanMapperUtil
一个接口:
BeanMapperUtil
Two implementing beans: 两个实现bean:
OrikaBeanMapper
- Singleton bean and marked @Primary
OrikaBeanMapper
单例豆并标记为@Primary
DirectBeanMapper
- prototype bean DirectBeanMapper
原型bean In Manager class: 在经理课程中:
@Autowired
BeanMapperUtil mapper;
Observation: Spring creates both OrikaBeanMapper
and DirectBeanMapper
and then autowires OrikaBeanMapper
. 观察: Spring同时创建
OrikaBeanMapper
和DirectBeanMapper
,然后自动装配OrikaBeanMapper
。
Expected: Since OrikaBeanMapper
is already marked as @Primary
, Spring should create only this bean and autowire it. 预期:由于
OrikaBeanMapper
已经被标记为@Primary
,Spring应该只创建这个bean并自动装配它。 Spring need not create an instance of DirectBeanMapper
. Spring不需要创建
DirectBeanMapper
的实例。 There is no impact on performance/functionality, but this looks like wasteful creation of instance only to be discarded. 这对性能/功能没有影响,但是这看起来像浪费实例的创建,只能将其丢弃。
When your application starts, Spring container creates instance of all the beans(expect prototype bean) which are register in that and stores that bean in the BeanFactory. 当您的应用程序启动时,Spring容器会创建所有在其中注册的bean(期望原型bean)的实例,并将该bean存储在BeanFactory中。
Hence all beans are created at once and only BeanMapperUtil is injected as it is used for autowiring. 因此,所有的bean都被立即创建,并且只有BeanMapperUtil被注入,因为它用于自动装配。
@Primary
works as a filter after all matching beans have been created. 创建所有匹配的bean之后,
@Primary
用作过滤器。 It's not designed to prevent the lookup and creation of other, non-primary, matching beans. 它并非旨在防止查找和创建其他非主匹配的Bean。
When Spring tries to autowire BeanMapperUtil
, it will find two matches, OrikaBeanMapper
and DirectBeanMapper
, and both will be created. 当Spring尝试自动
BeanMapperUtil
,它将找到两个匹配项OrikaBeanMapper
和DirectBeanMapper
,并且两者都将被创建。 At this point the @Primary
comes into play. 此时,
@Primary
开始起作用。 Spring will choose the bean with the @Primary
annotation for injection. Spring将选择带有
@Primary
批注的bean进行注入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.