[Translate]8-spring Bean's scope

Source: Internet
Author: User
Tags getmessage tutorialspoint

When you define a bean using the <bean/> tag in spring, you can use the Scope property to define the scope of the bean. If you want every time

A newly created bean instance from the spring container can be specified scope= "prototype", if you want each time from the spring container to get

To the same bean instance, you can specify scope= "singleton"

There are 5 kinds of scopes for beans in spring, including 3 for Web applications. The scope in 5 is described as follows:

Scope Description
Singleton Singleton Bean. Only one instance of the bean is in the entire IOC container
Prototype Prototypes. Each time a new bean is created from the spring IOC container
Request Each HTTP request creates a bean. For web apps only
Session A bean is shared with each session. Applies only to Web apps
Global-session The bean is instantiated only once throughout the Web application

In this article we only introduce Singleton and prototype scopes.

Singleton scope

Bean in spring IOC container if scope is specified as singleton, then the Bean will only have one instance in this IOC container.

The first time the bean is obtained from the spring IOC container, the spring IOC container instantiates and assembles the bean, and then the bean

Cached and later, when the bean is obtained from the spring IOC container, the IOC container returns the cached bean instance.

The following is an example of a singleton scope program.

1. Create the Com.tutorialspoint.scope.singleton package and create the Helloworld.java class in the package as follows:

 Package Com.tutorialspoint.scope.singleton;  Public class HelloWorld {        private  String message;      Public void setmessage (String message) {        this. Message = message;    }       Public void GetMessage () {        System.out.println ("Your message:" + message);}    }

2. In the SRC directory, create the Scope_singleton.xml configuration file with the following content:

In the configuration file, specify the scope of the bean as Singleton.

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd ">   <BeanID= "HelloWorld"class= "Com.tutorialspoint.scope.singleton.HelloWorld"Scope= "Singleton"/></Beans>

3. Create the Mainapp.java in the package Com.tutorialspoint.scope.singleton as follows:

 PackageCom.tutorialspoint.scope.singleton;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classMainapp { Public Static voidMain (string[] args) {//instantiate a spring IOC containerApplicationContext context =NewClasspathxmlapplicationcontext ("Scope_singleton.xml"); //from the container, get the HelloWorld bean with scope Singleton. And cast to HelloWorldHelloWorld Obja = (HelloWorld) context.getbean ("HelloWorld"); //call the Setmessage method of Obja to assign a value to the member variable messageObja.setmessage ("I am Object A"); //Print the OBJA member variable messageObja.getmessage (); //get the HelloWorld bean scoped to single again from the Spring IOC containerHelloWorld OBJB = (HelloWorld) context.getbean ("HelloWorld"); //directly get the OBJB member variable message, you can find that the OBJB message is also assigned, indicating that the same bean instance is obtained from the IOC containerObjb.getmessage (); //again, check to see if the objects referenced by Obja and OBJB are the same object, and from the printing information you can verify that Obja and OBJB are indeed the same objectSystem.out.println (obja==OBJB); }}

4. Run the program validation results as follows:

Finally we modify the Scope_singleton.xml configuration file, remove the scope= "singleton" and run the program again. Found two runs

The result is exactly the same. This proves that the scope of thebean managed by the spring IOC container is singleton by default

prototype Scope

The spring IOC container manages a scope of prototype beans, and each time a user requests the bean from the IOC container, it

A new instance of the bean is created and returned to the user. Generally the scope of a stateful bean is set to prototype; stateless

The bean's scope is set to Singleton. (You can simply think of a member variable, and the class that modifies the variable is stateful).

In the following experiment, the experiment code is exactly the same as the code in the singleton example, except that the configuration metadata is different. I'm just knocking it over.

1. Create a new package Com.tutorialspoint.scope.prototype and create a new Helloworld.java in the package as follows:

 Package Com.tutorialspoint.scope.prototype;  Public class HelloWorld {        private  String message;      Public void setmessage (String message) {        this. Message = message;    }       Public void GetMessage () {        System.out.println ("Your message:" + message);}    }

2. Create a new Scope_prototype.xml file in the SRC directory with the following contents:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd ">      <!--specifies that the scope scope of the HelloWorld Bean is prototype -   <BeanID= "HelloWorld"class= "Com.tutorialspoint.scope.prototype.HelloWorld"Scope= "Prototype"/></Beans>

3. Create a new class Mainapp.java in package com.tutorialspoint.scope.prototype with the following contents:

 PackageCom.tutorialspoint.scope.prototype;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classMainapp { Public Static voidMain (string[] args) {//instantiate a spring IOC containerApplicationContext context =NewClasspathxmlapplicationcontext ("Scope_prototype.xml"); //from the container, get the HelloWorld bean with scope prototype. and cast to HelloWorldHelloWorld Obja = (HelloWorld) context.getbean ("HelloWorld"); //set the message member variable of ObjaObja.setmessage ("I ' m object A"); //get the message member variable of ObjaObja.getmessage (); //get the HelloWorld bean scoped to prototype again from the Spring IOC containerHelloWorld OBJB = (HelloWorld) context.getbean ("HelloWorld"); //gets the member variable of the OBJB message. A message is found to be null, proving that Obja and OBJB are not the same instanceObjb.getmessage (); //further verify that the objects referenced by Obja and OBJB are the sameSystem.out.println (obja==OBJB); }}

4. Run the program, verify the results, and discover that the prototype bean in the IOC container will recreate the instance for each request.

[Translate]8-spring Bean's scope

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.