Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

java - Spring -- inject 2 beans of same type

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. I can mark my constructor with @Autowired and everything works fine, as long as I don't have two parameters of the same type. For example, I have a class:

@Component
public class SomeClass {
    @Autowired(required=true)
    public SomeClass(OtherClass bean1, OtherClass bean2) {
        …
    }
}

and an application context with:

<bean id="bean1" class="OtherClass" />
<bean id="bean2" class="OtherClass" />

There should be a way to specify the bean ID on the constructor of the class SomeClass, but I can't find it in the documentation. Is it possible, or am I dreaming of a solution that does not exist yet?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...