spring bean一共有几种作用域
系列文章目录
文章目录
- 系列文章目录
- 一、spring bean作用域
- 1、singleton
- 2、prototype
- 3、request
- 4、session
- 5、application-web应用专用
- 6、websocket-web应用专用
一、spring bean作用域
1、singleton
容器中只能创建一个bean实例,所有对该bean的引用都指向同一个对象
@Component
@Scope("singleton")
public class SingletonBean {private int count = 0;public void increment() {count++;}public int getCount() {return count;}
}@Autowired
private SingletonBean bean1;@Autowired
private SingletonBean bean2;// 输出 true,bean1 和 bean2 是同一个对象
System.out.println(bean1 == bean2);
2、prototype
每次从容器中获取bean时都会新建一个实例
@Component
@Scope("prototype")
public class PrototypeBean {private int count = 0;public void increment() {count++;}public int getCount() {return count;}
}@Autowired
private PrototypeBean bean1;@Autowired
private PrototypeBean bean2;// 输出 false,bean1 和 bean2 是不同的对象
System.out.println(bean1 == bean2);
3、request
每个http请求都会创建一个新的bean实例,请求结束后销毁,每个请求需要独立处理的数据如表单提交,用户信息,这个 Bean 只能在 Web 应用中使用(例如 Spring MVC 控制器中)
@Component
@Scope("request")
public class RequestBean {private String data;public void setData(String data) {this.data = data;}public String getData() {return data;}
}
4、session
每个 HTTP Session 创建一个 Bean 实例,Session 过期后销毁。只能用于web应用
@Component
@Scope("session")
public class SessionBean {private String user;public void setUser(String user) {this.user = user;}public String getUser() {return user;}
}
5、application-web应用专用
整个 Web 应用范围共享一个 Bean 实例,类似于 singleton,但作用域是 ServletContext。
@Component
@Scope("application")
public class ApplicationBean {private String configValue = "default";public String getConfigValue() {return configValue;}public void setConfigValue(String value) {this.configValue = value;}
}
6、websocket-web应用专用
每个 WebSocket 会话创建一个 Bean 实例,会话结束时销毁。应用场景是WebSocket 通信中需要维护会话状态的 Bean
@Component
@Scope("websocket")
public class WebSocketBean {private String message;public void setMessage(String message) {this.message = message;}public String getMessage() {return message;}
}
所有作用域(除了 singleton 和 prototype)都只能在 Web 应用 中使用(即 ApplicationContext 是 WebApplicationContext)