spring笔记8---单例bean和原型bean

默认情况下的bean都为单例bean,即context创建的时候就已经创建,我们可以通过设置bean的scope属性为singleton来设置bean为原型bean,使得实例在使用的时候才去创建,而且每次创建都是不同的实例。


1 新建User类如下:

package com.gm.spring_test;

public class User {
	private int age;
	private String name;

	@Override
	public String toString() {
		return "User [name = " + name + ", age = " + age + "]";
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

2 修改配置文件spring-conf.xml:




	

	
	

	
	
	
	



3 使用bean:

ApplicationContext context = new ClassPathXmlApplicationContext("spring-conf.xml");

User user1 = (User) context.getBean("User");
User user2 = (User) context.getBean("User");

User user11 = (User) context.getBean("User1");
User user12 = (User) context.getBean("User1");

User user21 = (User) context.getBean("User2");
User user22 = (User) context.getBean("User2");

if (user1 == user2) {
	System.out.println("user1 == user2");
} else {
	System.out.println("user1 != user2");
}

if (user11 == user12) {
	System.out.println("user11 == user12");
} else {
	System.out.println("user11 != user12");
}

if (user21 == user22) {
	System.out.println("user21 == user22");
} else {
	System.out.println("user21 != user22");
}


4 显示结果如下:

user1 == user2
user11 == user12
user21 != user22

通过结果可以看出,默认情况的bean是单例bean。

你可能感兴趣的:(Spring)