programing

Spring -- inject 2 beans of same type

codeshow 2023. 9. 9. 10:22
반응형

Spring -- inject 2 beans of same type

저는 주입된 필드를 만들 수 있기 때문에 건설자 기반 주입을 좋아합니다.final. 또한 주석 구동 주입을 통해 내 작업을 단순화할 수 있기 때문에 좋아요.context.xml. 나는 나의 시공자를 표시할 수 있습니다.@Autowired같은 종류의 매개변수가 두 개만 없다면 모든 것이 잘 작동합니다.예를 들어, 수업이 있습니다.

@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" />

클래스의 생성자에 bean ID를 지정할 수 있는 방법이 있어야 합니다.SomeClass, 설명서에서 찾을 수가 없네요.가능한가요, 아니면 아직 존재하지 않는 해결책을 꿈꾸고 있는 건가요?

@Autowired는 (이 경우) by-type입니다. 사용@Qualifier스프링 문서의 예에 따라 바이네임을 자동 배선합니다.

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)

ReferenceURL : https://stackoverflow.com/questions/2153657/spring-inject-2-beans-of-same-type

반응형