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));
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM