spring - Spring中RestController和Controller的作用域
问题描述
Spring 应用程序中 Controller 和 RestController 的范围应该是什么?如果是 Singleton,则为默认行为。但是不会让单个 bean 跨越来自多个客户端的请求/响应,因为我们的控制器将调用一些其他 bean(比如@Service)来处理用户特定的请求(比如从数据库或另一个 REST/SOAP 服务获取用户详细信息) .
解决方案
您在这里有两个选择:
选项 1 - 在您的服务类中,确保您不在实例变量中保存任何特定于请求的详细信息。而是将它们作为方法参数传递。
前任:
如果有同时请求,下面的代码将损坏存储在 userId 中的值。
@Service
public class SomeService {
String userId;
public void processRequest(String userId, String orderId) {
this.userId = userId;
// Some code
process(orderId);
}
public void process(String orderId) {
// code that uses orderId
}
}
同时,以下代码是安全的。
@Service
public class SomeService {
private String userId;
public void processRequest(String userId, String orderId) {
// Some code
process(userId, orderId);
}
public void process(String userId, String orderId) {
// code that uses userId and orderId
}
}
选项 2:
您可以将请求特定的数据保存在请求范围的 bean 中,并将它们注入您的单例中。Spring 为注入的请求范围 bean 创建一个代理,并代理对与当前请求关联的 bean 的调用。
@RequestScoped
class UserInfo {
}
@Service
class UserService {
@Autowired
private UserInfo userInfo;
public void process(String orderId) {
// It is safe to invoke methods of userInfo here. The calls will be passed to the bean associated with the current request.
}
}
推荐阅读
- ios - 不了解坐标/状态管理模式中的闭包用法
- dialogflow-es - Google dialogflow agent.add(new Suggestion()) 无法在 dialogflow Messenger 上运行
- powershell - 如何从 powershell 获取 .msi?
- java - 无法将纯 Java/Kotlin 模块添加到 Android Studio 4.1
- apache-spark - Apache Spark 中 DataFrame 写入格式 JDBC 中的列映射
- c# - 在同一按钮 WPF C# 上调用 MouseDown 事件后,MouseUp 事件处理程序不起作用
- android - GoogleSignIn requestPermissions onActivityResult 0 with Google Fitness steps/distance Scope
- firemonkey - C++ Builder 中的 Android JNI
- javascript - 获取嵌套数组中值最高的前 5 个元素
- react-native - 如何在 React Native 中返回变量?