Bean的作用域
在IOC里创建对象的时候,同一个类,只会创建一个实例对象,多次获取同一个类的对象时,实际上获取的都是同一个对象,
两个对象的地址是相同的
car.java
package com.labou3g.bean.scope;
public class Car {
private String brand;
private double price;
public Car() {
System.out.println("我是构造方法....");
}
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;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
}
情景一
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 id="car" class="com.labou3g.bean.scope.Car">
<property name="brand" value="赤兔马"></property>
<property name="price" value="1000"></property>
</bean>
</beans>
Test.java
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-autowire.xml");
Car car1 = (Car)ctx.getBean("car");
Car car2 = (Car)ctx.getBean("car");
System.out.println(car1 == car2);
}
}
运行结果
情景二
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 id="car" class="com.labou3g.bean.scope.Car" scope="singleton">
<property name="brand" value="赤兔马"></property>
<property name="price" value="1000"></property>
</bean>
</beans>
运行结果
和情景一结果一直,因为scope的默认值就是singleton
情景三-prototype
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 id="car" class