Bean Scopes

Bean Scopes

官方文档

Scope Description
singleton (Default) Scopes a single bean definition to a single object instance for each 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 . Only valid in the context of a web-aware Spring .Session``ApplicationContext
application Scopes a single bean definition to the lifecycle of a . Only valid in the context of a web-aware Spring .ServletContext``ApplicationContext
websocket Scopes a single bean definition to the lifecycle of a . Only valid in the context of a web-aware Spring .WebSocket``ApplicationContext

1.单例模式 (默认机制是单例)

辛格尔顿

代码实例(用的之前的beans.xml文件)

image-20260317164457061

 com.wjj.pojo.Student student =(Student) context.getBean("student");
 com.wjj.pojo.Student student2 =(Student) context.getBean("student");
 System.out.println(student.hashCode());
 System.out.println(student2.hashCode());
 System.out.println(student.equals(student2));

2.圆形模式 (xml文件改动)

prototype

image-20260317165203901

<bean id="student" class="com.wjj.pojo.Student" scope="prototype">
posted @ 2026-03-17 20:37  三咲肘击王  阅读(7)  评论(0)    收藏  举报