Spring并在运行时将参数传递给factory-method [英] Spring and passing parameters to factory-method in runtime
问题描述
方法context.getBean(name,user)的文档说
The documentation of method context.getBean(name, user) says
允许指定显式构造函数参数/工厂方法
参数
Allows for specifying explicit constructor arguments / factory method arguments
但无论我做什么(尝试过所有事情),最合乎逻辑的设置我在加载bean时得到这个在初始化期间启动:
but no matter what I do (tried everything), with the most logical setting I get this when the beans are being loaded up during initialization:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'fileValidator' defined in
PortletContext resource
[/WEB-INF/classes/context/customer-form-portlet.xml]: Unsatisfied
dependency expressed through constructor argument with index 0 of type
[com.liferay.portal.model.User]: Ambiguous factory method argument
types - did you specify the correct bean references as factory method
arguments?
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'fileValidator' defined in
PortletContext resource
[/WEB-INF/classes/context/customer-form-portlet.xml]: Unsatisfied
dependency expressed through constructor argument with index 0 of type
[com.liferay.portal.model.User]: Ambiguous factory method argument
types - did you specify the correct bean references as factory method
arguments?
<bean id="fileValidator"
class="cz.instance.transl.validation.file.FileValidator"
factory-method="createInstance" />
private FileValidator(User user) {
this.user = user;
}
public static FileValidator createInstance(User user) {
return new FileValidator(user);
}
评论说你可以这样做,但是如果你在xml中指定构造函数参数无论是否定义该bean,它都会失败。
The commentary says you can do it, but if you specify constructor arguments in xml definiton of that bean or not, it fails.
推荐答案
javadoc 说:
args - 使用静态工厂方法的显式参数创建原型时使用的参数。
args - arguments to use if creating a prototype using explicit arguments to a static factory method.
因此bean定义必须是一个原型范围的bean,即
So the bean definition must be a prototype-scoped bean, i.e.
<bean id="fileValidator"
scope="prototype"
class="cz.instance.transl.validation.file.FileValidator"
factory-method="createInstance" />
这篇关于Spring并在运行时将参数传递给factory-method的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!