SpringIOC创建对象的单例和多例模式

问题:

Spring容器对象根据配置文件创建对象的时机默认发生在Spring容器对象在被创建的时候,也就是说,我们一旦获取到Spring容器对象,意味着可以直接获取Spring容器中的对象使用了.那么,如果我对同一个bean对象,连续获取N次,获取到的是不是同一个对象呢?因为spring容器对象底层使用的是map集合存储的bean对象,对map集合按照同一个键名获取数据,获取的是同一个,也就说按照同一个键名从Spring容器中获取的都是同一个对象,那么如果我们希望相同的键名获取的对象每次都不一样,怎么实现?

解决:

不要在Spring容器对象创建的时候,就完成对象的初始化创建,而是变为,从Spring容器中获取的时候才创建,每次获取都重新创建.

实现:

Spring容器的单例和多例模式创建对象.

单例模式(默认):

设置了单例模式的bean,会在Spring容器对象被创建的时候 就完成初始化创建,无论获取多少次都是同一个对象.

多例模式:

设置了多例模式的bean,在Spring容器对象被创建的时候不会被初 始化创建,每次获取的时候都会重新创建,每次获取的对象都不相同.

使用:

applicationcontext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--
    SpringIOC设置对象的单例模式和多例模式创建对象
    单例模式:默认模式,在bean标签上使用scope属性,默认值为singleton
    多例模式:在bean标签上使用scope属性设置,值为prototype
    -->
    <bean id="stu" class="com.bjsxt.pojo.Student" scope="singleton"></bean>
    <bean id="tea" class="com.bjsxt.pojo.Teacher" scope="prototype"></bean>
</beans>

  

package com.bjsxt.controller;
import com.bjsxt.pojo.User;
import com.bjsxt.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.rmi.CORBA.StubDelegate;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @author wuyw2020
 * @date 2020/1/8 20:55
 */
@WebServlet(value = "/user", loadOnStartup = 1)
public class UserServlet extends HttpServlet {
   
    public static void main(String[] args) {
        //获取Spring容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");
        Student stu =(Student) ac.getBean("stu");
        Student stu2 =(Student) ac.getBean("stu");
        
        Teacher teacher = (Teacher) ac.getBean("stu");
        Teacher teacher2 = (Teacher) ac.getBean("stu");
        System.out.println("学生:"+(stu==stu2));
        System.out.println("教室:"+(teacher==teacher2));
    }
}

  

原文地址:https://www.cnblogs.com/vincentmax/p/14298702.html