Spring Singleton VS prototype

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

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

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

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


    看看下面的一个实例:

    首先定义一个CustomerService类。

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是默认值,因此不写也行):




    

运行它吧!

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

打印信息:

Message : Message by custA
Message : Message by custA


看吧,果然是同一个bean。


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

...
    
...

再运行main:

Message : Message by custA
Message : null

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

你可能感兴趣的:(Spring)