【问题标题】:How to make spring @Value attribute session scoped如何使 spring @Value 属性会话范围
【发布时间】:2018-08-12 18:16:30
【问题描述】:

我有一个 application.properties 文件,其中包含以下内容:

retry.count = 3

注入到 Spring MVC 控制器中

@Value("${retry.count}")
private int retryCount;

try{
  invokeRestCall()
}
catch(TimeOutException ex){
  if(retryCount > 0) {
  retryCount--;
  //Retry call with recursion
  }
}

由于 retryCount 是在应用程序加载时注入的,而不是会话范围内的,所以 retryCount 在会话之间共享并且计数器不起作用

bean 的范围可以由@Scope(value="session") 定义,但这不适用于@Value 属性并显示错误“无法为字段定义范围”

还有其他方法可以使字段会话范围吗?

【问题讨论】:

  • 当您将@Scope(value="session") 放在类级别时,该字段不会成为会话范围吗?

标签: java spring spring-mvc spring-boot


【解决方案1】:

你应该看看Spring-retry

使用它,您可以避免管理该状态并使您的组件无状态,因此,将其设为 Singleton 而不是 Session-scoped

【讨论】:

    【解决方案2】:

    Two parallel HTTP sessions do not share the changes done in session scoped bean instances.(source)。您应该在拥有此字段的类上方添加 @Scope 会话。然后每个新的 http 会话都会获得自己的类实例,从而获得自己的 retryCount 版本

    【讨论】:

      猜你喜欢
      • 2012-05-21
      • 2013-01-17
      • 2016-01-15
      • 1970-01-01
      • 2011-02-06
      • 2011-09-02
      • 2014-12-02
      • 2011-10-16
      • 1970-01-01
      相关资源
      最近更新 更多