Spring Autowiring @Qualifierの例
Springでは、@ Qualifierは、どのBeanがフィールドで自動配線される資格があるかを意味します。 次のシナリオを参照してください。
自動配線の例
以下の例を参照してください。「個人」Beanを顧客の個人プロパティに自動配線します。
package com.example.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Customer {
@Autowired
private Person person;
//...
}
ただし、2つの類似したBean「com.example.common.Person」がBean構成ファイルで宣言されています。 Springは、どの人のBeanが自動配線されるべきかを知っていますか?
上記の例を実行すると、例外の下にヒットします:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [com.example.common.Person] is defined:
expected single matching bean but found 2: [personA, personB]
@Qualifierの例
上記の問題を修正するには、@Quanlifierを使用して、どのBeanを自動配線する必要があるかをSpringに通知する必要があります。
package com.example.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Customer {
@Autowired
@Qualifier("personA")
private Person person;
//...
}
この場合、Bean「personA」は自動配線されます。
Customer [person=Person [name=exampleA]]
ソースコードをダウンロード
ダウンロード–Spring-AutoWiring-Qualifier-Example.zip(6 KB)