Spring — inject 2 beans of same type

前端 未结 1 889
一整个雨季
一整个雨季 2020-12-14 00:08

I like constructor-based injection as it allows me to make injected fields final. I also like annotation driven injection as it simplifies my context.xml<

相关标签:
1条回答
  • 2020-12-14 00:34

    @Autowired is by-type (in this case); use @Qualifier to autowire by-name, following the example from spring docs:

    public SomeClass(
        @Qualifier("bean1") OtherClass bean1, 
        @Qualifier("bean2") OtherClass bean2) {
        ...
    }
    

    Note: In contrast to @Autowired which is applicable to fields, constructors and multi-argument methods (allowing for narrowing through qualifier annotations at the parameter level), @Resource is only supported for fields and bean property setter methods with a single argument. As a consequence, stick with qualifiers if your injection target is a constructor or a multi-argument method.

    (below that text is the full example)

    0 讨论(0)
提交回复
热议问题