Spring学习 之 bean的作用域(单例singleton 和 原型prototype)

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="car1" class="autowrite.Car" scope="singleton">
		<property name="brand" value="car1"></property>
	</bean>
	
	<bean id="car2" class="autowrite.Car" scope="prototype">
		<property name="brand" value="car2"></property>
	</bean>
</beans>

Car.java

package autowrite;

public class Car {
	
	private String brand;
	public Car() {
		super();
		System.out.println("Car 的构造函数。。。。。。");
	}
	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;
	}
	@Override
	public String toString() {
		return "Car [brand=" + brand + ", price=" + price + "]";
	}
	
	

}

scopeMain.java

package scope;

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

import autowrite.Car;

public class scopeMain {

	public static void main(String[] args) {

		System.out.println("ClassPathXmlApplicationContext加载 before。。。。。。");
		
		ApplicationContext ac = new ClassPathXmlApplicationContext("scope.xml");
		
		System.out.println("ClassPathXmlApplicationContext加载 after。。。。。。");
		
		Car car1 = (Car)ac.getBean("car1");
		Car car2 = (Car)ac.getBean("car1");
		
		System.out.println("scope='singleton'的结果是:"+(car1==car2));
		
		System.out.println("\n========================================================\n");
		
		car1 = (Car)ac.getBean("car2");
		car2 = (Car)ac.getBean("car2");
		
		System.out.println("scope='prototype'的结果是:"+(car1==car2));
	}

}
发布了30 篇原创文章 · 获赞 0 · 访问量 3692

猜你喜欢

转载自blog.csdn.net/MENGCHIXIANZI/article/details/104107230