方法 context.getBean(name, user) 的文档说
Allows for specifying explicit constructor arguments / factory method arguments
但无论我做什么(尝试了一切),在初始化过程中加载 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 - arguments to use if creating a prototype using explicit arguments to a static factory method.
因此 bean 定义必须是原型(prototype)范围的 bean,即
<bean id="fileValidator"
scope="prototype"
class="cz.instance.transl.validation.file.FileValidator"
factory-method="createInstance" />
关于java - Spring 并在运行时将参数传递给工厂方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6784960/