Within a bean's configuration you can specify a property scope, which is the bean's scope, the bean's life cycle.
Scope desirable values 5 kinds: Singleton ( default ), prototype, request, session, global session
Among the most commonly used are: Singleton and prototype, and the other three are web-related and rarely used.
Singleton: This is the singleton mode. Indicates that the bean is a singleton pattern, and each fetch is the same bean
Prototype: multiple cases, that is, every time you get a new object, use the scene: you need to set it to prototype on the action
For example: User This bean, the default scope property we are not configured, that is, Singleton mode
| 123456 |
<bean name="user" class="com.fz.entity.User" > <property name="id" value="1"></property> <property name="username" value="fangzheng"></property> <property name="password" value="123456"></property> <property name="role" ref="role"></property></bean> |
Test Singleton, the result is true
| 1234567 |
@Testpublic void getProperties(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); User user1 = (User) ctx.getBean("user"); User user2 = (User) ctx.getBean("user"); System.out.println(user1 == user2);//结果为true } |
Add Scope=prototype
After adding Scope=prototype to <bean>.
| 123456 |
<bean name="user" class="com.fz.entity.User" scope="prototype"> <property name="id" value="1"></property> <property name="username" value="fangzheng"></property> <property name="password" value="123456"></property> <property name="role" ref="role"></property></bean> |
Test prototype, the result is false
| 1234567 |
@Testpublic void getProperties(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); User user1 = (User) ctx.getBean("user"); User user2 = (User) ctx.getBean("user"); System.out.println(user1 == user2);//结果为false} |
From for notes (Wiz)
Bean's life cycle scope in spring