Aug 3rd, 2006, 05:11 AM
getObject() on FactoryBean with singleton product
I have implemented a FactoryBean that returns singleton instance and returns true from isSingleton().
The product of this factory is set as a property on two other beans. It seems that the getObject method on the factory bean is called 3 times - once on initialization of the factory bean itself, and then once each on the initialization of the two beans with the dependencies on it.
from the javadoc for FactoryBean.isSingleton():
"If a FactoryBean indicates to hold a singleton object, the object returned from getObject() might get cached by the owning BeanFactory. Hence, do not return true unless the FactoryBean always exposes the same reference."
I would have thought, therefore, that the reference returned from the first call to getObject() would have been cached (although i do note the word "might"). Why is this not the case in this situation? What dictates whether or not references to singletons from factory beans are cached?
I'm using 1.2.8 and the container is a ClassPathXmlApplicationContext.
Aug 3rd, 2006, 05:50 AM
Hi, this surprised me too when I had to use this feature.
It seems the isSingleton property is merely an indication of how your BeanFactory is implemented. So set this to true when you always return the same Object, false otherwise.
If you want caching you have to implement this in your BeanFactory implementation manually.