Spring中的RestController和Controller的范围

时间:2018-05-20 21:40:19

标签: spring scope controller javabeans

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

1 个答案:

答案 0 :(得分:0)

这里有两个选项:

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