Spring bean scopes example

Source: Internet
Author: User
Spring bean scopes exampleposted on March 26,201 0

By mkyong

In spring, bean scope is used to decide which type of bean instance shocould be return from spring container back to the caller.

5 types of bean scopes supported:

  1. Singleton-return a single bean instance per Spring IoC container
  2. Prototype-return a new bean instance each time when requested
  3. Request-return a single bean instance per HTTP request .*
  4. Session-return a single bean instance per http session .*
  5. Globalsession-return a single bean instance per global http session .*

In most cases, you may only deal with the spring's core scope-singleton and prototype, and the default scope is Singleton.

P.s * means only valid in the context of a Web-aware spring applicationcontext

Singleton vs prototype

Here's an example to show you what's the different between bean scope:SingletonAndPrototype.

package com.mkyong.customer.services; public class CustomerService {String message; public String getMessage() {return message;} public void setMessage(String message) {this.message = message;}}
1. Singleton example

If no bean scope is specified in bean configuration file, default to Singleton.

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">        <bean id=""             class="com.mkyong.customer.services.CustomerService" /> </beans>

Run it

package com.mkyong.common; import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext; import com.mkyong.customer.services.CustomerService; public class App {    public static void main( String[] args )    {    ApplicationContext context =      new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});     CustomerService custA = (CustomerService)context.getBean("customerService");    custA.setMessage("Message by custA");    System.out.println("Message : " + custA.getMessage());     //retrieve it again    CustomerService custB = (CustomerService)context.getBean("customerService");    System.out.println("Message : " + custB.getMessage());    }}

Output

Message : Message by custAMessage : Message by custA

Since the bean 'mermerservice' is in singleton scope, the second retrieval by 'custb' will display the message set by 'custa' also, even it's retrieve by a new getbean () method. in Singleton, only a single instance per spring
IOC container, no matter how many times you retrieve it with getbean (), it will always return the same instance.

2. Prototype example

If you want a new 'mermerservice' bean instance, every time you call it, use prototype instead.

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">    <bean id="customerService" class="com.mkyong.customer.services.CustomerService"          scope="prototype"/> </beans>

Run it again

Message : Message by custAMessage : null

In prototype scope, you will have a new instance for eachgetBean()Method
Called.

3. Bean scopes Annotation

You can also use annotation to define your bean scope.

package com.mkyong.customer.services; import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Service; @Service@Scope("prototype")public class CustomerService {String message; public String getMessage() {return message;} public void setMessage(String message) {this.message = message;}}

Enable auto component Scanning

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd">        <context:component-scan base-package="com.mkyong.customer" /> </beans>
Download source codedownload it-Spring-Bean-Scopes-Example.zip (7 kb) Reference
  1. Http://static.springsource.org/spring/docs/2.0.x/reference/beans.html#beans-factory-scopes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.