首页 > 解决方案 > Spring中RestController和Controller的作用域

问题描述

Spring 应用程序中 Controller 和 RestController 的范围应该是什么?如果是 Singleton,则为默认行为。但是不会让单个 bean 跨越来自多个客户端的请求/响应,因为我们的控制器将调用一些其他 bean(比如@Service)来处理用户特定的请求(比如从数据库或另一个 REST/SOAP 服务获取用户详细信息) .

标签: springscopecontrollerjavabeans

解决方案


您在这里有两个选择:

选项 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.
    }
}

推荐阅读