来自这个 Q/A:如何在 Spring 中定义 List bean?我知道我可以定义一个List<Foo> fooList
填充Foo
bean 实例但使用 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
也不与 Spring 类紧密耦合。此外,就我而言,我不能使用任何 Java EE 类,如本博文所示:Spring 2.5.x+3.0.x: Create prototype instances from code。BeanFactory
FooClient
javax.inject.Provider