欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-03 12:32:42
...

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

}

 

相关标签: spring 基础