從這個問題:How to define a List bean in Spring?我知道我可以定義一個填充了Foo
bean實例但使用XML配置的List<Foo> fooList
。這裏有一個例子:如何使用註釋創建充滿原型bean實例的列表?
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類的解決方案。另外,對於我的情況,我不能使用任何Java EE類,如javax.inject.Provider
,如本博文所示:Spring 2.5.x+3.0.x: Create prototype instances from code。
你想創造出許多在列表中的同一個bean的? –
您可以創建許多帶註釋的setter注入,每個注入的setter類型都是bean,並將bean添加到封裝列表中 –
您的List中原型的實例數量是多少? –