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.