0

I have an object to be scoped as a prototype, and the constructor argument values are determined at runtime. It seems to me that I have to use a static factory method to construct an instance of this prototype. Is this true, and where in the documentation might I find it stating that fact? I couldn't find anything discussing constructor values or references determined at runtime. All of the samples have explicitely defined values at startup.

2 Answers2

2

Fundamentally what needs to be done is:

applicationContext.getBean("beanName", new Object[]{arg1, arg2, arg3});

<bean id="beanName" class="my.package.className" scope="prototype">
  <constructor-arg index="0" type="java.lang.String" value=""/>
  //etc
</bean>

If your classes are otherwise spring-free and you don't want that applicationContext dependency mucking them up, then a factory method may be desirable.

You could also use Method Replacement to isolate the spring-dependant code.

Affe
  • 47,174
  • 11
  • 83
  • 83
  • It is interesting this works because the documentation for this method for the args parameter says: "arguments to use if creating a prototype using explicit arguments to a static factory method. It is invalid to use a non-null args value in any other case." That is what made me think that call to getBean could only be used for objects created using static factory methods. –  Jun 27 '12 at 19:17
  • 1
    Ya, I guess the Parameters section of the java doc isn't the most meticulously maintained thing ever :) The method comment does say it can be either constructor args or factory method args: "Allows for specifying explicit *constructor arguments* / factory method arguments, overriding the specified default arguments (if any) in the bean definition." – Affe Jun 27 '12 at 20:16
  • Thanks for the additional info... I'm just glad it works at this point :) –  Jun 27 '12 at 20:18
0

Check out lookup-method (4.4.6.1 Lookup method injection). Currently it does not support passing arguments to newly created prototype beans, but this will soon be possible.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674