java - Spring 并在运行时将参数传递给工厂方法

标签 java spring factory-method

方法 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/

相关文章:

java - Jtable 中的单元格样式

java - 如何创建 Java 自定义 Web 控件?

Java正则表达式匹配器动态字符串问题

mysql - Hibernate更改数据库从oracle更改为mysql

java - PersistenceAnnotationBeanPostProcessor 是否会以某种方式影响环境或@PropertySource?

java - 工厂方法模式的优势

java - 在java中扩展参数化工厂方法

java - hashCode()、equals() 在维护 Set 中用户定义对象的唯一性时的行为?

java - 将请求范围定义为集成测试的原型(prototype)

java - 设计模式 : Factory vs Factory method vs Abstract Factory