View RSS Feed

Spring Framework

Understanding the Difference Between Singleton vs. Prototyping of Spring Beans

Rate this Entry
by , 11-16-2011 at 04:13 PM (9785 Views)
When you configure a new Spring beanBy default, all Spring beans are singletons. When the container dispenses a bean, it will always give the exact same instance of the bean. But sometimes you want the application context to return a unique instance for each time you request a specific bean. In this case, you would want to do is to define a prototype bean. When you define a prototype means that you define a blueprint of the bean. Every subsequent bean for this requested bean will be based on this specific blueprint. The singleton property of <bean> tells the application context whether or not a bean is to be defined as a singleton. By default it is set to true, but setting it to false results in a bean being defined as a prototype:

Java Code:
<bean id=”car” class=”com.acme.springexamples.domain.Car” singleton=”false”/>
Prototyped beans are useful when you want the container to give a unique instance of a bean each time it is asked for, but you still want to configure one or more properties of that bean through Spring. So going back to our previous tip involving CarDao if you define singleton=false, this will change the carDao bean’s definition so that a new instance is created every time it is needed:

Java Code:
<bean id="carDao" class="com.acme.springexamples.dao.CarDaoImpl" singleton="false"/>
Note that a new instance of a prototype bean will be created each time getBean() is invoked with the bean’s name. If you have limited resources and the bean for which you have created as a prototype is for a database or network resource, you can create serious problems for yourself. At worst, you will incur a small performance hit each time a new instance is created. So only define beans as prototypes when it is absolutely necessary. In my experience, it is most useful when you are using the Spring context as a factory for domain objects, like the one for a Car shown above. Since they are prototype beans, they will be easy to configure the objects at the factory level (like any other bean), while still guaranteeing that the factory would dispense a unique instance each time you ask for a domain object.

Submit "Understanding the Difference Between Singleton vs. Prototyping of Spring Beans" to Facebook Submit "Understanding the Difference Between Singleton vs. Prototyping of Spring Beans" to Digg Submit "Understanding the Difference Between Singleton vs. Prototyping of Spring Beans" to del.icio.us Submit "Understanding the Difference Between Singleton vs. Prototyping of Spring Beans" to StumbleUpon Submit "Understanding the Difference Between Singleton vs. Prototyping of Spring Beans" to Google

Comments