Are Spring Controllers Thread-Safe

前端 未结 4 1350
你的背包
你的背包 2021-02-05 18:21

I came upon this Controller example, and am wondering if it is thread-safe? I am wondering specifically about the gson instance variable.

import org.springframe         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 18:45

    Assuming that this controller is created as a normal Spring "singleton" bean, the answer is no.

    You could create the controller as a prototype bean, in which case a new instance would be created for each request. A better idea, if you want to do this, is to define your bean's scope as request.

    However, I question the reason for any controller object to have member variables, aside from the possibility of incorrectly scoping the bean. It's an indication that the controller is trying to do too much work, and that some of that work should be offloaded to a service or helper class. The only things that an MVC controller should do arepass request data on to a service layer, and retrieve data to be displayed by a view.

提交回复
热议问题