重新认识Spring的Scope

Spring的Sope是什么

Scope,也称作用域,在 Spring IoC 容器是指其创建的 Bean 对象相对于其他 Bean 对象的请求可见范围。在 Spring IoC 容器中具有以下几种作用域:基本作用域(singleton、prototype),Web 作用域(reqeust、session、globalsession),自定义作用域。

  1. singletonConfigurableBeanFactory.SCOPE_SINGLETON,单例模式,也为默认模式;
  2. prototypeConfigurableBeanFactory.SCOPE_PROTOTYPE,多例模式;
  3. requestWebApplicationContext.SCOPE_REQUEST,表示在一次http请求中,被注解的Bean都是同一个Bean,不同的请求是不同的Bean;
  4. sessonWebApplicationContext.SCOPE_SESSION,表示在一次http会话中,被注解的Bean都是同一个Bean,不同的会话是不同的Bean;

prototype陷阱

正常情况下singleton为单例,prototype为多例,若直接在入口位置即使用prototype属性,那么对应的实例确实会有多个。但是若prototype修饰的类对象为其他singleton修饰的对象对应的属性,则prototype起不到真正的想要结果。因为本应该为多例的对象,被单例对象首次加载的时候已经赋予在内存里.

@Scope(“prototype”)的正确用法——解决Bean的多例问题

Spring中原型prototype的准确使用

但实际上prototype并不是不对,也不是出了问题,而是我们的使用方式有问题。

如何处理prototype属性不起效的问题

  1. 正常情况下,直接使用@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS),可以实现真正的多例模式。但是若业务内存在异步操作,且请求相关的http丢失,则会报错.
Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

I am getting the above error when i am injecting a spring dependency and using it inside MessageListener bean
  1. 直接使用SpringBeanUtil获取对应Bean;

    对于嵌套Scope情形,通过getApplicationContext().getBean()方式,获取bean对象,若对象为prototype,则会按照Bean的生成策略,生成多例对象。
  2. 上面的两种方式,要么可能存在问题,要么感觉不怎么优雅。这里还有一个方法。
@Autowired
ObjectFactory<BalanceLogic> balanceLogicFactory

直接使用

BalanceLogic balanceLogic = balanceLogicFactory.getObject();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值