【Spring】(3.2)bean對象的作用域

一、作用域

Spring中bean有6種作用域(singleton、prototype、request、session、application、websocket),該篇文章僅講前兩種。

項目結構:

在這裏插入圖片描述

兩個實體類

public class Customer {
}
public class User {
}

pojos.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 默認創建bean對象就是單例的(默認這一句就是加上的:scope="singleton") -->
    <bean id="user" class="com.shengjava.pojo.User" scope="singleton"></bean>

    <!-- 修改爲prototype,此時每次創建的對象都是一個新對象 -->
    <bean id="customer" class="com.shengjava.pojo.Customer" scope="prototype"></bean>

</beans>

測試:

public class UserTest {
    @Test
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("pojos.xml");

        User user1 = context.getBean("user", User.class);
        User user2 = context.getBean("user", User.class);
        Customer customer1 = context.getBean("customer", Customer.class);
        Customer customer2 = context.getBean("customer", Customer.class);
        System.out.println(user1 == user2);
        System.out.println(customer1 == customer2);
    }
}

輸出:

因爲user1和user2作用域都是singleton單例的,他倆是一個對象,所以輸出true。

而customer1和customer2作用域爲prototype,每次獲取都是以惡個新對象,並不相等,所以輸出false。

true
false

參考官方文檔:
1.5. Bean Scopes


相關

我的該分類的其他相關文章,請點擊:【Spring + Spring MVC + MyBatis】文章目錄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章