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

}

 

發佈了21 篇原創文章 · 獲贊 0 · 訪問量 3426
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章