scope属性
scope表示spring容器对一个bean的请求的处理方式,我们常用的设置值有:singleton(默认的)和prototype
singleton
在容器中,从请求bean到容器生命周期结束,有且仅有一个bean的实例,每次请求都返回这个,所以对应生命周期从创建到容器销毁
prototype
每次请求bean,容器都会给生成一个新的实例并返回,返回后容器就不负责这个实例的管理。实例的生命周期就给请求方去管理来。
我们看的简单的例子
配置文件
<?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 id="helloWorld" class="com.test.Car" scope="singleton">
<property name="brand" value="Spring"/>
</bean>
</beans>
Car类
public class Car {
private String brand;
private String color;
private int maxSpeed;
public Car() {
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
}
调用程序
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) throws Throwable {
ApplicationContext ctx=new ClassPathXmlApplicationContext("file:applicationContext.xml");
Car helloWorld=(Car) ctx.getBean("helloWorld",Car.class);
Car helloWorld1=(Car) ctx.getBean("helloWorld",Car.class);
System.out.println(helloWorld==helloWorld1);
System.out.println(helloWorld.toString());
System.out.println(helloWorld1.toString());
}
}
输出
true
com.xxx.Car@49c342bd
com.xxx.Car@49c342bd
两次获取的实例都是同一个,我们把配置文件中的
scope="singleton"
修改成
scope="prototype"
后,输出如下:
false
com.xxx.Car@5aba9dff
com.xxx.Car@11dafee2
获取实例是不一样的