Passing Parameters to Bean Constructors
Hi Everyone
I've seen beans where people use construtors in the beans and i have seen beans where they keep the constructors blank -- as advised to by SUN documents.
Would you happen to know specifically why people are advised not to use constructors in beans ?
my guess, is that setting properties in the constructor would demand that a new bean be created everytime a bean is needed.
but i'm thinking that if the bean is only used in page and request scope -- and is not saved to disk or anything like that, then constructors in the beans might be okay .
what do you think ?
I just ask because i have seen examples with parameters in the constructor.
Stephen
Hi !!
If you use the <jsp:usebean ...> tag directive , and if the scope of the bean used is just the page, then the bean is instantiated only once , which means that the constructor is called only once. Setting properties does not create new instances of the bean.Also once the user leaves the JSP page via a re-direct or a URL , then the garbage collector kicks in a removes the bean instance from the server's heap memory.But Every re-visit or refresh to the page causes the bean to be instantiated again. This is not the case if the lifetime of the bean instance is specified as a session or request. So to conclude, there is no problem in using constructors in Beans , but remember the act of using a constructor should be meaningful , such as creating a connection to a database or pre-loading a hashtable or some such task which is best done "once" !!!!
Regards
Chandu
I don't know if this is what Stephen meant, but I'm wondering about using parameterized constructors for beans in a jsp.
If you have a bean like the following:
public class MyBean{
public MyBean(){
// some stuff
}
public MyBean( String param ){
// some other stuff
}
}
As far as I can tell, there is no way to call this second constructor using the <jsp:useBean> syntax. Similarly, there is no way to pass a parameter to a "getter" method in the bean using the <jsp:getProperty> tag.
I know that a bean ideally is just a collection of data members with get() and set() methods for each, (meaning that parameterized constructors and get() methods aren't necessary) but there are times that passing a param to a bean would be convenient, such as when the bean's property is a collection or array and you only want one element. In this case there is no way (that I can see) to avoid using scriptlets, and the whole idea of jsp tags is to minimize the amount of java code in the jsp, right? So what's up with that?