有状态的Bean和无状态的Bean
来源:11-5 SpringIOC的getBean方法的解析

pookly
2023-07-27
老师您好,请问:课程的SpringBean作用域部分提到的有状态的Bean和无状态的Bean有什么区别?怎么区分?分别适用什么场景?
写回答
1回答
-
翔仔
2023-08-02
同学好,根据spring官网的定义
stateless beans: beans that are singleton and are initialized only once. The only state they have is a shared state. These beans are created while the ApplicationContext is being initialized.
stateful beans: beans that can carry state (instance variables). These are created every time an object is required.
翻译过来其实就是没有状态的bean是单例且初始化一次,变量是共享的。
有状态的bean是携带实例变量的,即bean实例有多个,每个有独立的变量。
应用场景有状态的主要就是跟一些会话状态相关,比如每次请求来就new一个bean,携带当前会话的专属的变量(session_id等),用来跟踪本次会话的
00
相似问题