Saturday, December 13, 2014

Dealing with parameterized constructor in spring

1.   Class Tester :  

package samples.experiment;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Tester {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Dispatcher-servlet.xml");
        PrintString s=(PrintString)context.getBean("stringPrinter",new Object[]{"Sanjeevan"});
        s.printString();
}

}

=======================================
2.   Class PrintString  

package samples.experiment;

public class PrintString {
private String s;
PrintString() {
System.out.println("Default consrtructor invoked");
}

PrintString(String s) {
this.s=s;
System.out.println("Input got in constructor is : " + s);
}
}
=======================================

3. Dispatcher-servlet.xml

<bean id="stringPrinter" class="samples.experiment.PrintString" scope="prototype"/>


=======================================

OUTPUT

Input got in constructor is : Sanjeevan
Entered the string method os PrintSring class : Sanjeevan


Error:

When you are not using scope="protype" in 
<bean id="stringPrinter" class="samples.experiment.PrintString"/>, 
then you will be getting the error as follows.

org.springframework.beans.factory.BeanDefinitionStoreException: Can only specify arguments for the getBean method when referring to a prototype bean definition


This is because , by default the scope is singleton and so spring will try to create object even before the first request for the object, where it cant get the constructor parameter from user.


No comments :

Post a Comment