Share on Google+Share on Google+

Spring Bean Scope Prototype

In this tutorial you will learn about Spring Bean Scope Prototype

Spring Bean Scope

There are five different types of bean scopes (i.e. singleton, prototype, request, session, global session) supported by the spring framework. Apart of these five the Spring?s core scope is singleton and prototype. The singleton return a single bean instance per spring IoC container and the prototype return a new bean instance each time when requested. In this example it demonstrate the concept of prototype.

package spring.bean.scope.singleton;

public class SimpleBean {
	String message;

	public String getMessage() {
		return message;

	public void setMessage(String message) {
		this.message = message;

package spring.bean.scope.prototype;

import org.springframework.context.ApplicationContext;
import spring.bean.scope.prototype.SimpleBean;

class AppMain {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "context.xml" });

		SimpleBean bean1 = (SimpleBean) context.getBean("simplebean2");
		bean1.setMessage("Message by bean1");
		System.out.println("Message : " + bean1.getMessage());

		SimpleBean bean2 = (SimpleBean) context.getBean("simplebean2");
		System.out.println("Message : " + bean2.getMessage());

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
  xmlns:xsi="" xmlns:aop=""

<!-- prototype -->
<bean id="simplebean2" class="spring.bean.scope.prototype.SimpleBean" scope="prototype"/> 

When you run this application it will display message as shown below:

Message : Message by bean1
Message : null

Download this example code


Posted on: August 30, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null