【问题标题】:Scope of RestController and Controller in SpringSpring中RestController和Controller的作用域
【发布时间】:2018-05-20 21:40:19
【问题描述】:
Spring应用中Controller和RestController的范围应该是什么?如果是 Singleton,则为默认行为。但是不会让单个 bean 跨越来自多个客户端的请求/响应,因为我们的控制器将调用一些其他 bean(比如@Service)来处理用户特定的请求(比如从数据库或另一个 REST/SOAP 服务获取用户详细信息) .
【问题讨论】:
标签:
spring
scope
controller
javabeans
【解决方案1】:
你有两个选择:
选项 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.
}
}