Spring @Primary

傷城~ 2024-03-22 15:40 118阅读 0赞

Sometimes we need to define multiple beans of the same type. In these cases, the injection will be unsuccessful because Spring has no clue which bean we need.

方案1:@Qualifier
方案2:@Primary

  1. @Component
  2. @Primary
  3. class Car implements Vehicle {
  4. }
  5. @Component
  6. class Bike implements Vehicle {
  7. }
  8. @Component
  9. class Driver {
  10. @Autowired
  11. Vehicle vehicle;
  12. }
  13. @Component
  14. class Biker {
  15. @Autowired
  16. @Qualifier("bike")
  17. Vehicle vehicle;
  18. }

发表评论

表情:
评论列表 (有 0 条评论,118人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Spring中@Primary注解

    1.概述 讨论Spring的@Primary注解,该注解是框架在3.0版中引入的。 其作用与功能,当有多个相同类型的bean时,使用@Primary来赋予bean更高的