SpringIOC建立物件的單例和多例模式
阿新 • • 發佈:2021-01-19
問題:
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)); } }