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

猜你喜欢

转载自blog.csdn.net/weixin_41577923/article/details/85051053