【问题标题】:How to use field in @Component class simultaneously?如何同时使用@Component 类中的字段?
【发布时间】:2023-03-19 01:37:02
【问题描述】:

遵循此代码:

@Component
public class ClassC extends ClassA<T> implements ClassB {

    private String preferredDateTimeFormat = null;

我的进程在调用客户端的请求后正在使用这个类。

对于每个请求,我想保留 preferredDateTimeFormat 值,实际上是在做什么,preferredDateTimeFormat 变量正在用于我的所有请求。

我能做些什么来解决它?

【问题讨论】:

  • 你可以让你的问题更清晰
  • 如何使每个ClassC(@Component)实例的preferredDateTimeFormat字段不同
  • 你的意思是有不同的价值?
  • 这个@Component 的每个实例对于preferredDateTimeFormat 变量应该有不同的值
  • 你想用范围(请求)注释你的类。由于 Spring 默认初始化单例 bean。

标签: java spring


【解决方案1】:

在你的类上使用@Scope,值=request

喜欢这个

@Component
@Scope(value="request", proxyMode =ScopedProxyMode.TARGET_CLASS)
public class ClassC extends ClassA<T> implements ClassB {

  private String preferredDateTimeFormat = null;

你可以找到更多关于 Spring Bean Scopes 的信息here

【讨论】:

  • 那个有效,你能给我一些关于 - @Scope(value="request", proxyMode =ScopedProxyMode.TARGET_CLASS) 目的的简短信息吗?
【解决方案2】:

有多种方法。

您可以定义一个请求范围 bean 并将preferredDateTimeFormat 放在那里。

或

您可以定义 ThreadLocal 属性并将值放在那里。

【讨论】:

    【解决方案3】:

    我不完全确定您的意思是每次请求都需要一个 ClassC 实例,还是每次使用它时都需要一个新实例,但您可能需要查看 @Scope 注释及其值 Prototype 和 Request。

    见Spring Bean Scopes。

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多