この Q/A から: Spring で List Bean を定義する方法は? List<Foo> fooList
Bean インスタンスで満たされたものを定義できることはわかっていFoo
ますが、XML 構成を使用しています。次に例を示します。
public interface Foo {
//methods here...
void fooMethod();
}
@Service("foo")
@Scope("prototype")
public class FooImpl implements Foo {
//fields and methods...
@Override
public void fooMethod() {
//...
}
}
@Service("fooCache")
@Scope
public class FooCacheImpl implements Foo {
//fields and methods...
@Override
public void fooMethod() {
//retrieves data from some cache
//...
}
}
@Service("fooWS")
@Scope("prototype")
public class FooWSImpl implements Foo {
//fields and methods...
@Override
public void fooMethod() {
//retrieves data from web service
//...
}
}
XML を使用してクライアントを構成できます。
<bean id="fooClient" class="some.package.FooClient">
<property name="fooList">
<list>
<bean ... /> <!-- This may be fooImpl -->
<bean ... /> <!-- This may be fooCacheImpl -->
<bean ... /> <!-- This may be fooWSImpl -->
<!-- I can have more beans here -->
</list>
</property>
</bean>
これが注釈のみで実行できるかどうかを知りたいのですが、XML で Bean を定義する必要はありません。このようなもの:
@Component
@Scope("prototype")
public class FooClient {
//which annotation(s) to use here to fill this list with FooImpl instances?
//I understand that if I have two implementations of Foo I may use a @Qualifier
//or use another list to note the different implementations.
private List<Foo> fooList;
public void bar() {
for (Foo foo : fooList) {
foo.fooMethod();
}
}
}
の注入を伴わないソリューションの方が良いと思いますApplicationContext
のでBeanFactory
、FooClient
Spring クラスに密接に結合されていません。また、私の場合、javax.inject.Provider
次のブログ投稿に示されているような Java EEクラスを使用することはできません。