Spring basics-Bean scope, spring basics bean

Source: Internet
Author: User

Spring basics-Bean scope, spring basics bean

1. In the Spring Config file, set the bean scope in the scope attribute of the <Bean> element. The default value is singleton.

2. the scope attribute has only two values without introducing the spring-web-4.0.0.RELEASE.jar package: singleton and prototype.

1. singleton (singleton)

Spring creates an instance for each Bean declared in the IOC container, and the entire IOC container scope can be shared. The object returned through getBean () is the same object.

For example:

<bean class="com.nucsoft.spring.bean.Employee" id="employee" p:empName="emp01" p:age="12"/>
@Testpublic void test01() {  Employee employee = ctx.getBean(Employee.class);  System.out.println(employee);  Employee employee2 = ctx.getBean(Employee.class);  System.out.println(employee2);}

Console output:

Com. nucsoft. spring. bean. Employee @ 1ed71887
Com. nucsoft. spring. bean. Employee @ 1ed71887

2. prototype (prototype). Each call to getBean () will return a new instance.

<bean class="com.nucsoft.spring.bean.Employee" id="employee" p:empName="emp01" p:age="12" scope="prototype"/>
@Test public void test01() {  Employee employee = ctx.getBean(Employee.class);  System.out.println(employee);  Employee employee2 = ctx.getBean(Employee.class);  System.out.println(employee2);}

Console output:

Com. nucsoft. spring. bean. Employee @ 652e3c04
Com. nucsoft. spring. bean. Employee @ 3e665e81

 

We will not discuss the scope of Bean in the web environment here. In fact, we usually use these two types.

 

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.