Spring and passing parameters to factory-method in runtime

lisak picture lisak · Jul 22, 2011 · Viewed 61.3k times · Source

The documentation of method context.getBean(name, user) says

Allows for specifying explicit constructor arguments / factory method arguments

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);
}

The commentary says you can do it, but if you specify constructor arguments in xml definiton of that bean or not, it fails.

Answer

skaffman picture skaffman · Jul 22, 2011

The javadoc says:

args - arguments to use if creating a prototype using explicit arguments to a static factory method.

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" />