java 如何自动装配 factorybean
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2153298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to autowire factorybean
提问by Paul McKenzie
I have a ServiceListFactoryBean which creates a list of service implementations:
我有一个 ServiceListFactoryBean,它创建了一个服务实现列表:
<bean id="services"
class="org.springframework.beans...ServiceListFactoryBean"
p:serviceType="ServiceInterface"/>
I can access the services using the applicationContext without a problem:
我可以毫无问题地使用 applicationContext 访问服务:
final List services = ctx.getBean("services", List.class));
I can also use trad constructor-arg injection successfully:
我也可以成功使用 trad 构造函数参数注入:
<bean id="aClass" class="AClass">
<constructor-arg ref="services"/>
</bean>
But if I try to autowire the dependency
但是如果我尝试自动装配依赖项
@Autowired @Qualifier("services") private List services;
Then I get a BeanCreationExceptioncaused by
然后我得到一个BeanCreationException由
FatalBeanException: No element type declared for collection [java.util.List]
I am using Spring 3.0.
我正在使用 Spring 3.0。
回答by Paul McKenzie
It turns out that the answer is ...
原来答案是……
@Resource(name="services") private List services;
回答by skaffman
The exception message is from DefaultListableBeanFactory, and it's complining that it can't autowire your field because the Listhas no generic type (see DefaultListableBeanFactoryline 716).
异常消息来自DefaultListableBeanFactory,并且它无法自动装配您的字段,因为List它没有通用类型(请参阅DefaultListableBeanFactory第 716 行)。
Try adding a generic signature to your field, e.h.
尝试在您的字段中添加一个通用签名,嗯
@Autowired @Qualifier("services") private List<Service> services;
回答by nefo_x
what i actually found out today, is that when you need map of bean names to instances of specific interface, there is no need of @Qualifier's and any sort of FactoryBeancode. Spring would find and inject candidates for you. @Resourcedidn't do it's job, just in case.
我今天实际发现的是,当您需要将 bean 名称映射到特定接口的实例时,不需要@Qualifier's 和任何类型的FactoryBean代码。Spring 会为你寻找并注入候选人。@Resource没有做它的工作,以防万一。

