// shall I write some keywords here to boost search engine ranking?

Sunday, October 26, 2008

Spring: factory method with arguements

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


mvmn said...

It's a documented feature.

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

mks4blb said...

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!

Hei said...

i think is opaque for a non-newbie as well. Thanks for posting

capitale said...

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.

Anonymous said...

Thanks for the post. It is listed in a very simple manner making understanding it easy.


Sri said...

what if my constructor doesn't have any arguments?

Ta bu shi da yu said...

Sri, if your constructor has no arguments then just make it:

Anonymous said...

Can you please site an example of appcontext.xml file having a factory-method having multiple type of arguments!!