在运行时将参数和参数传递给工厂方法
问题内容:
方法context.getBean(name,user)的文档说
允许指定显式构造函数参数/工厂方法参数
但是无论我做什么(尝试一切),使用最合理的设置在初始化期间加载Bean时都会得到以下信息:
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);
}
注释说可以做到的,但是如果您在该bean的xml定义中指定构造函数参数,则失败。
问题答案:
在javadoc中说:
args-在使用静态工厂方法的显式参数创建原型时使用的参数。
因此,bean的定义 必须 是原型作用域的bean,即
<bean id="fileValidator"
scope="prototype"
class="cz.instance.transl.validation.file.FileValidator"
factory-method="createInstance" />