读书人

Spring 中的scope prototype与simplet

发布时间: 2012-08-29 08:40:14 作者: rapoo

Spring 中的scope prototype与simpleton的区别
Spring 中的scope prototype与simpleton的区别

首先在applicationContext.xml文件中:


在ScopeSample.java中:
package Spring.t02;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ScopeSample {
private String first;
private String second;
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSecond() {
return second;
}
public void setSecond(String second) {
this.second = second;
}
public ScopeSample(String first, String second) {
System.out.println(" two arguments constructor.....");
this.first = first;
this.second = second;
}
public ScopeSample() {
System.out.println(" no argument constructor.....");

}
public ScopeSample(String first) {

this.first = first;
System.out.println(" one argument constructor.....");
}
public void doInit(){
System.out.println("init .....");
}
public void doDestroy(){
System.out.println(" destroy.....");
}
public static void main(String[]args){
ApplicationContext ac=new
ClassPathXmlApplicationContext("applicationContext.xml");
ScopeSample s1=(ScopeSample)ac.getBean("scopeSample");
ScopeSample s2=(ScopeSample)ac.getBean("scopeSample");//当sope为prototype的时候会调用两次构造方法,
System.out.println("s1==s2?"+(s1==s2));

}
}

在ScopeSample2.java当中:
package Spring.t02;
public class ScopeSample2 {
private String name="";
public void setName(String name) {
this.name = name;
}
public ScopeSample2(String name) {
super();
this.name = name;
System.out.println(" ScopeSample2 one arg construtctor .... ");
}
public ScopeSample2() {

super();
System.out.println(" ScopeSample2 no arg construtctor .... ");
// TODO Auto-generated constructor stub
}
public void doInit(){
System.out.println(this.getClass()+" init....");
}

}
当 scope类型是simpleton的时候:
运行ScopeSample.java输出结果:
two arguments constructor.....
init .....
ScopeSample2 no arg construtctor ....
class Spring.t02.ScopeSample2 init....
s1==s2?true
当scope类型为prototype类型的时候,运行结果是:
ScopeSample2 no arg construtctor ....
class Spring.t02.ScopeSample2 init....
two arguments constructor.....
init .....
two arguments constructor.....
init .....
s1==s2?false
这两次运行结果比较可以总结:
当scope是simpleton的时候, 那么Spring
IOC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。换言之,当把一个bean定义设置为singleton作用域时,Spring
IOC容器只会创建该bean定义的唯一实例。
所以虽然在ScopeSmaple.java中调用了两次getBean但只调用了一次构造方法和init方法
当scope是prototype 的时候,每一次请求获得Bean的时候(即调用geiBean方法的时候)就创建一次对象(即调用构造方法),并调用init方法。
两者的区别还有一点:
我们看到上面两个例子的输出顺序也不一样,注意在加载applicationContext.xml 文件的时候
scope=simpleton(默认情况下)的时候不用请求获得bean就会调用构造方法创建对象,
但是scope=prototype的时候请求获得bean的时候才会去创建对象

本文转载:
http://hi.baidu.com/zhuyuli521/blog/item/fb61990e31c310206059f311.html

读书人网 >软件架构设计

热点推荐