Spring framework is a popular IoC framework. In the documentation, it show examples of instatiate object through constructor, static factory method, and instance factory method.
However, It do not show the example of factory method with parameters. After some google, below is the trick:
public class TestObject{
private String id;
private TestObject(String id){
super();
this.id = id;
}
public static TestObject getInstance(String id){
return new TestObject(i)
}
}
<bean id="testObject" class="TestObject" factory-method="getInstance">
<constructor-arg type="java.lang.String" value="object-id-123"/>
</bean>
8 comments:
It's a documented feature.
See:
http://static.springsource.org/spring/docs/2.0.x/reference/beans.html
"Note that arguments to the static factory method are supplied via constructor-arg elements, exactly the same as if a constructor had actually been used."
It may be a documented feature of Spring, but the documentation is somewhat opaque for a newbie. Worked like a charm for me. Thanks for posting!
i think is opaque for a non-newbie as well. Thanks for posting
thanks for pointing this out! even though it's present in the official documentation, it's misplaced and one would have to read a lot to find it by accident. Not handy at all if you're just searching for a specific feature.
Thanks for the post. It is listed in a very simple manner making understanding it easy.
Thanks,
satish
what if my constructor doesn't have any arguments?
Sri, if your constructor has no arguments then just make it:
Can you please site an example of appcontext.xml file having a factory-method having multiple type of arguments!!
Post a Comment