1. 程式人生 > >Spring 學習(七)——Bean 的作用域

Spring 學習(七)——Bean 的作用域

Spring , 可以在 <bean> 元素的 scope 屬性裡設定 Bean 的作用域.

預設情況下, Spring 只為每個在 IOC 容器裡宣告的 Bean 建立唯一一個例項, 整個 IOC 容器範圍內都能共享該例項所有後續的 getBean() 呼叫和 Bean 引用都將返回這個唯一的 Bean 例項.該作用域被稱為 singleton, 它是所有 Bean 的預設作用域.

car.java

package com.hzyc.spring.bean.autowire;

/**
 * @author xuehj2016
 * @Title: Car
 * @ProjectName spring01
 * @Description: TODO
 * @date 2018/12/1710:30
 */
public class Car {
    private String brand;
    private double price;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public Car() {
        System.out.println("Car's Constructor...");
    }
}

bean-scope.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">

    <!--
        使用 bean 的 scope 屬性來配置 bean 的作用域
        singleton : 預設值,容器初始化時建立 bean 的例項,在整個容器的生命週期內只建立這一個 bean ,單例的
        prototype : 原型的,容器初始化時不建立 bean 的例項,而在每次請求時建立一個新的 bean 例項,並返回
    -->
    <bean id="car" class="com.hzyc.spring.bean.autowire.Car" scope="prototype">
        <property name="brand" value="寶馬"/>
        <property name="price" value="450000"/>
    </bean>
</beans>

Main.java

package com.hzyc.spring.bean.scope;

import com.hzyc.spring.bean.autowire.Car;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author xuehj2016
 * @Title: Main
 * @ProjectName spring01
 * @Description: TODO
 * @date 2018/12/1618:01
 */
public class Main {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean-scope.xml");

        Car car = (Car) applicationContext.getBean("car");
        System.out.println(car);

        Car car2 = (Car) applicationContext.getBean("car");
        System.out.println(car2);

        System.out.println(car == car2);
    }
}