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

版权声明:仅供学习交流使用 https://blog.csdn.net/drxRose/article/details/84944433

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

猜你喜欢

转载自blog.csdn.net/drxRose/article/details/84944433