1. 程式人生 > >spring ioc---bean的作用域(scope)

spring ioc---bean的作用域(scope)

xsd官方文件中,對標籤bean的屬性scope的說明:

The scope of this bean: typically "singleton" (one shared instance, which will be returned by all calls to getBean with the given id), or "prototype" (independent instance resulting from each call to getBean). By default, a bean will be a singleton, unless the bean has a parent bean definition in which case it will inherit the parent's scope. Singletons are most commonly used, and are ideal for multi-threaded service objects. Further scopes, such as "request" or "session", might be supported by extended bean factories (e.g. in a web environment). Inner bean definitions inherit the scope of their containing bean definition, unless explicitly specified: The inner bean will be a singleton if the containing bean is a singleton, and a prototype if the containing bean is a prototype, etc.

4.3.20版本的官方文件中,對scope候選值的解釋:

Scope Description
singleton (Default) Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
request
Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
globalSession Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a Portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

補充說明:實際使用中,較為常用的即單例和多例的候選值,其中單例的`singleton`是容器中預設的.

bean類

package siye;
public class User
{
}
package siye;
public class Person
{
}

配置檔案,config.xml

<bean class="siye.Person" scope="singleton" /> 
<bean class="siye.User" scope="prototype" />   

測試類

package siye;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UnitTest
{
	public static void main(String[] args)
	{
		String path = "classpath:/siye/config.xml";
		ClassPathXmlApplicationContext context =
				new ClassPathXmlApplicationContext(path);
		User user0 = context.getBean(User.class);
		User user1 = context.getBean(User.class);
		System.out.println(user0 == user1);// false
		Person person0 = context.getBean(Person.class);
		Person person1 = context.getBean(Person.class);
		System.out.println(person0 == person1);// true
		context.close();
	}
}