Spring in Bean scopes have five different types of singleton, prototype, request, session, globalSession. Where the request, session, globalSession these three scopes are only used to in web development.
When defining a bean in the Spring, you have the option to scope the bean statement, if not declared, the default scope is singleton.
The scope of the bean 1 singleton defined limits in a single instance of each Spring IoC container.
* Use: do nothing, the default is singleton, but you can also add a scope display, for example:
<bean id="user" class="com.zhbit.pojo.User" scope="singleton"/>
If you still do not understand what is a singleton, then give an example to illustrate:
@Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans2.xml"); User user = context.getBean("user", User.class); User user2 = context.getBean("user", User.class); System.out.println(user==user2); }
operation result:
The output is true. Proven user and user2 is the same object!
Conclusion: As long as scope of the bean is singleton, getBean () method with the same parameters of a bean id, the instance of that object is the same.
<bean id="user" class="com.kuang.pojo.User" scope="prototype"/>
Exemplified:
@Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans2.xml"); User user = context.getBean("user", User.class); User user2 = context.getBean("user", User.class); System.out.println(user==user2); } }
The output is false, proven user and user2 is not the same object.