spring_(7)bean的作用域

  1. 这一小节讲的是,当你在xml配置了一个bean,Main.java中创建两个这个对象时,这两个对象时一样的,也就是demo1==demo2 为 true.

  2. 原因在于配置bean的时候 属性scope默认为singleton,假设改为prototype,这两个对象将不再相等

    demo1==demo2 为 false

例子程序

基本结构

在这里插入图片描述

Car.java

package com.spring.beans.autowire;

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

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}

beans-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.spring.beans.autowire.Car" scope="prototype">
        <property name="brand" value="Audi"></property>
        <property name="price" value="300000"></property>
    </bean>
</beans>

Main.java

package com.spring.beans.relation;

import com.spring.beans.autowire.Address;
import com.spring.beans.autowire.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args){

        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-relation.xml");

        Address address = (Address) ctx.getBean("address2");
        System.out.println(address );

        address = (Address) ctx.getBean("address3");
        System.out.println(address);

        Person person = (Person) ctx.getBean("person");
        System.out.println(person);

    }
}

运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42036647/article/details/84172144