在Spring中,bean可以被定义为两种模式:prototype(多例)和singleton(单例)
singleton(单例):只有一个共享的实例存在,所有对这个bean的请求都会返回这个唯一的实例。
prototype(多例):对这个bean的每次请求都会创建一个新的bean实例,类似于new。
Spring bean 默认是单例模式。
简单来说,spring中的单例是通过单例注册表实现的。
实战演示:
代码详见上一篇文章中的代码。
在配置文件中,修改这句代码为:
1 <bean id="hi" class="com.test.Hi" init-method="init" scope="singleton">
1
在测试类中,修改代码为:
1 ApplicationContext context = new FileSystemXmlApplicationContext("applicationContext.xml");
2 Hi hi1 = (Hi) context.getBean("hi");
3 Hi hi2 = (Hi) context.getBean("hi");
4 System.out.println(hi1);
5 System.out.println(hi2);
1
2
3
4
5
结果为:
结论:二个变量指向一个对象。
将配置文件改为:
<bean id="hi" class="com.test.Hi" init-method="init" scope="prototype">
1
其他的不变,运行测试类,结果为:
结论:每次访问bean,均创建一个新实例。
Spring怎么实现单例模式
单例模式也属于创建型模式,所谓单例,顾名思义,所指的就是单个实例,也就是说要保证一个类仅有一个实例。
单例模式有以下的特点:
①单例类只能有一个实例
②单例类必须自己创建自己的唯一实例
③单例类必须给所有其他对象提供这一实例
下面我们就来写一个简单的单例模式的例子:
Public class Singleton1{
Private static final Singleton1 instance=new Singleton1();
//私有的默认构造函数
Public Singleton1(){}
//静态工厂方法
Public static Singleton1 getInstance(){
Return instance;
}
}
1
2
3
4
5
6
7
8
9
大家可以看出来,在这个类被加载时,静态变量instance会被初始化,此时该类的私有构造函数被调用,这时候,单例类的唯一实例就被创建出来了
值得注意的是:由于构造函数是私有的,因此该类不能被继承
还有一种写法也可以实现单例模式:
Public class Singleton2{
Private static final Singleton2 instance=null;
//私有的默认构造函数
Public Singleton1(){}
//静态工厂方法
Public synchronized static Singleton2 getInstance(){
If(instance==null){
Instance=new Singleton2();
}
Return instance;
}
}
1
2
3
4
5
6<