Car.java

package com.gong.spring.beans.autowire;

public class Car {
    
    public Car() {
    }

    public Car(String name) {
        this.name = name;
    }
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Car [name=" + name + "]";
    }
    
}

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"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="car" class="com.gong.spring.beans.autowire.Car" p:name="baoma"></bean>
</beans>

Main.java

package com.gong.spring.beans.autowire;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        //1.创建spring的IOC容器对象
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-scope.xml");
        //2.从容器中获取Bean实例
        Car car = (Car) ctx.getBean("car"); 
        Car car2 = (Car) ctx.getBean("car");
        System.out.println(car == car2);
        System.out.println(car.toString());
    }
}

输出:

spring之bean的作用域_java

默认情况下,在xml文件中配置的bean都是单例模式,即实例化这个相同类型的bean时,返回的是同一个对象,即实例化IOC容器ctx时,就已经创建好了一个唯一的bean。我们可以在xml中设置scope属性的值来改变bean的作用域。

<bean id="car" class="com.gong.spring.beans.autowire.Car" p:name="baoma" scope="prototype"></bean>

scope有四种值:

spring之bean的作用域_实例化_02

默认的就是singleleton,在指定为prototype之后,每次实例化的对象就不是同一个bean了。

spring之bean的作用域_xml_03