Difference between @Primary vs @Autowired with @Qualifier annotations

前端 未结 3 773
野性不改
野性不改 2021-01-30 22:27

So, if I understood correctly, both are the way to determine which bean to autowire if there are multiple candidates. So what exactly is the difference?

3条回答
  •  攒了一身酷
    2021-01-30 23:10

    @Qualifier should be used in conjuction with @Autowired always. This will indicate the bean name which needs to be Autowired in case of multiple beans with same type is present in the application context.(so that spring can autowire by name.)

    @Primary should be used in conjuction with @Bean / @Autowired which indicates which bean should be given higher preference, when there are multiple beans of same type is present.

    One of the classic use cases where you would use @Primary is when the framework(example spring-data) expects a bean of some type (example EntityManager) but you have multiple datasources and you would have configured multiple Entity Managers. In such cases @Qualifier doesn't quite help.

提交回复
热议问题