Spring - Bean scopes

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.

 

2 prototype, at the time of acquisition Bean every request, will create a new instance, it will not create an instance when the container initialization, using the lazy loading in the form of injection Bean, when you use, will be instantiated of each instance of the object obtained is not the same.
*use:
   <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);
    }
}

 

operation result:

 

The output is false, proven user and user2 is not the same object.

 

3 request, creates an instance of every http request, only the current instance of the http request is valid
4 session, creates an instance of every http request, only the current instance of the http session is valid
5 globalSession, global Session, for different portlet sharing, portlet seems to be similar to the servlet Web components

Guess you like

Origin www.cnblogs.com/bear7/p/12530699.html