简体   繁体   中英

Spring: Two beans implementing one interface with one as @Primary - autowiring creates both beans

One Interface: BeanMapperUtil

Two implementing beans:

  1. OrikaBeanMapper - Singleton bean and marked @Primary
  2. DirectBeanMapper - prototype bean

In Manager class:

@Autowired
BeanMapperUtil mapper;

Observation: Spring creates both OrikaBeanMapper and DirectBeanMapper and then autowires OrikaBeanMapper .

Expected: Since OrikaBeanMapper is already marked as @Primary , Spring should create only this bean and autowire it. Spring need not create an instance of 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.

Hence all beans are created at once and only BeanMapperUtil is injected as it is used for autowiring.

@Primary works as a filter after all matching beans have been created. It's not designed to prevent the lookup and creation of other, non-primary, matching beans.

When Spring tries to autowire BeanMapperUtil , it will find two matches, OrikaBeanMapper and DirectBeanMapper , and both will be created. At this point the @Primary comes into play. Spring will choose the bean with the @Primary annotation for injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM