简体   繁体   English

Spring Rest应用程序中的Java静态/全局变量

[英]Java static/global variables in Spring Rest Application

I'm working on a Spring Rest Service Web application where as soon as a HTTP request is received in controller I set a static String variable null .我正在开发一个 Spring Rest Service Web 应用程序,只要在控制器中收到 HTTP 请求,我就会设置一个static String变量null Further in application, this variable is modified multiple times by various classes and methods, and in the end, this is returned as rest service response.进一步在应用中,这个变量被各种类和方法多次修改,最终作为rest服务响应返回。

I'm afraid that this static String variable might be updated by another concurrent HTTP request resulting in incorrect value in previous request.我担心这个static String变量可能会被另一个并发 HTTP 请求更新,从而导致先前请求中的值不正确。

I don't wish to use instance variable as that would need to be passed to multiple methods (>30) across the application.我不希望使用实例变量,因为它需要跨应用程序传递给多个方法(> 30)。

Please suggest a way to declare a global variable which is not updated by any concurrent HTTP request and have a separate copy for each HTTP request.请提出一种声明全局变量的方法,该变量不会被任何并发 HTTP 请求更新,并为每个 HTTP 请求提供一个单独的副本。

All your validation methods already take a parameter, right?你所有的验证方法都已经接受了一个参数,对吧? The data to be validated.要验证的数据。

They also all need the ability to generate validation messages and store them somewhere, eg in a "result collector", right?他们也都需要能够生成验证消息并将它们存储在某个地方,例如在“结果收集器”中,对吗? So that should be a parameter too.所以这也应该是一个参数。

Side note: Giving both the data and the result collector to the validators as parameters allows you to unit test the validators.旁注:将数据和结果收集器作为参数提供给验证器允许您对验证器进行单元测试

I don't see the problem with passing the result collector around to all the validators, the same way you're passing the data to be validated around.我没有看到将结果收集器传递给所有验证器的问题,就像传递要验证的数据一样。 It's how the code should have been written to begin with.这就是代码应该如何编写的开始。

Never use "global" memory in a web application.切勿在 Web 应用程序中使用“全局”内存。

Viewed purely from a validators point of view, you pass in the data to be validated, but expect the result to be written to a static collector?纯粹从验证器的角度来看,您传入要验证的数据,但希望将结果写入静态收集器? Bad design , right there.糟糕的设计,就在那里。 The validator should not be responsible for figuring out how to find the result collector.验证器不应该负责弄清楚如何找到结果收集器。

The controller has a singleton scope, it should not contain a data.控制器有一个单例范围,它不应该包含数据。 If you need to store data to to the application use the corresponding scope of the bean containing the data string.如果您需要将数据存储到应用程序,请使用包含数据字符串的 bean 的相应范围。

If you are using a bean which is shared among other users then the data should be protected from concurrent modifications.如果您使用的是在其他用户之间共享的 bean,则应保护数据免受并发修改。 Which way you provide the protection to users is not important at the moment but affordable data structures simplify the implementation of such beans.您以哪种方式为用户提供保护目前并不重要,但负担得起的数据结构简化了此类 bean 的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM