Saturday 19 March 2011

Spring : Factory methods with parameters

There are 2 ways of passing parameters to the factory-methods

  • by xml
  • by code

By Xml

Consider this bean:

public class TestObject{  

private String id;

private TestObject(String id){
super();
this.id = id;
}

public static TestObject getInstance(String id){
return new TestObject(i)
}
}

Now in the config file just use constructor-arg for this:

<bean id="testObject" class="TestObject" factory-method="getInstance">
<constructor-arg type="java.lang.String" value="object-id-123"/>
</bean>


By Code


In the context creating file write this :


ApplicationContext container = new ClassPathXmlApplicationContext("/some path/config.xml");
TestObject obj = (TestObject) containter.getBean("testObject","myParameter");

No comments:

Post a Comment