Spring Singleton VS prototype

2014-11-24 11:49:49 · 作者: · 浏览: 11

在Spring中,bean的作用域范围有5种,它们是[singleton,prototype,request,session,globalSession],其中singleton是默认值。

在大多数情况下,我们只和singleton和prototype打交道。那么,它们之间有什么区别呢?

singleton: 如单例模式一样,调用getBean()方法试图从IoC容器中返回唯一的实例。

prototype:每次调用getBean()方法,都从IoC容器中返回一个新建的实例。


看看下面的一个实例:

首先定义一个CustomerService类。


[java]
package org.spring.scope;

public class CustomerService {

private String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

}

package org.spring.scope;

public class CustomerService {

private String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

}

在Spring的bean配置文件中定义一个作用域为singleton的bean(因为singleton是默认值,因此不写也行):

[html]
< xml version="1.0" encoding="UTF-8" >
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">


< xml version="1.0" encoding="UTF-8" >
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">


运行它吧!


[java]
package org.spring.scope;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"SpringConfig.xml"});

CustomerService custA = (CustomerService)context.getBean("customer");
custA.setMessage("Message by custA");
System.out.println("Message : " + custA.getMessage());

//重新获取一遍
CustomerService custB = (CustomerService)context.getBean("customer");
System.out.println("Message : " + custB.getMessage());
}
}

package org.spring.scope;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"SpringConfig.xml"});

CustomerService custA = (CustomerService)context.getBean("customer");
custA.setMessage("Message by custA");
System.out.println("Message : " + custA.getMessage());

//重新获取一遍
CustomerService custB = (CustomerService)context.getBean("customer");
System.out.println("Message : " + custB.getMessage());
}
}

打印信息:


[plain]
Message : Message by custA
Message : Message by custA

Message : Message by custA
Message : Message by custA


看吧,果然是同一个bean。


如果把Spring的bean配置文件中的作用域修改为prototype:


[html]
...

...

...

...

再运行main:


[plain]
Message : Message by custA
Message : null

Message : Message by custA
Message : null

第二个消息为null,说明该bean不是之前获取的那个bean,而是在IoC容器新建的一个新bean。