Home Tutorial Spring Spring3 Ioc Spring Bean Scope Default

 
 

Spring Bean Scope Default
Posted on: August 30, 2010 at 12:00 AM
In this tutorial you will learn about Spring Bean Scope Default

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 singleton.

SimpleBean.java

package spring.bean.scope.singleton;

public class SimpleBean {
	String message;

	public String getMessage() {
		return message;
	}

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

AppMain.java

package spring.bean.scope.prototype;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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("simplebean1");
		bean1.setMessage("Message by bean1");
		System.out.println("Message : " + bean1.getMessage());

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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<!-- Singleton -->
<!--<bean id="simplebean1" class="spring.bean.scope.singleton.SimpleBean" scope="singleton"/> -->

</beans>

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


Message : Message by bean1
Message : Message by bean1

Download this example code

Related Tags for Spring Bean Scope Default:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.