Spring Learning record (v) scope Of---beans scope

Source: Internet
Author: User
Tags sessions

Scope:
Singleton: singleton, Only one instance is created throughout the application (default)

prototype: prototype, Create a new instance each time you inject

session: sessions, Creating one instance per session

request: requests, Each request creates an instance

By default , beans are singleton, initialized at the following time, invoking the constructor of each bean

1  <BeanID= "person"class= "com.guigu.spring.autowire.Person"2 P:name= "Tom" ></Bean>3 //equivalent to:4  <BeanID= "person"class= "com.guigu.spring.autowire.Person"5 P:name= "Tom"Scope= "singleton"></Bean>

1   New Classpathxmlapplicationcontext ("scope.xml");  Here initialize, call the Bean's constructor 2person   person1 = (person) ctx.getbean (' person '3 Person   person2 = (person) ctx.getbean (' person '4   system.out.println (person1 = = person2);  Result: true

In the first row, the constructor is called, the object is instantiated, and there is only one object. Person1 and Person2 are actually the same object.

If the prototype :

1   <  id= "person"  class= "com.guigu.spring.autowire.Person"2       p:name= "Tom"  scope= "prototype"></Bean  >

similarly, two calls, The result will be false

1    New Classpathxmlapplicationcontext ("scope.xml");  // initialized here, But no instance is created at this time 2    Person Person1 = (person) Ctx.getbean (' person '3person    person2 = (person) Ctx.getbean (' person ') c11>4    system.out.println (person1 = = person2);  // result: false

Prototype specifies that when the container is initialized, the instance is not created automatically, but instead is created when it is Called. Two calls were made, and two instances were created.

session: The same bean is the same as the one in the sessions, and the different session is different bean

Request: Generate a new bean for each HTTP request

Spring Learning record (v)---bean scope 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.