小编典典

Spring MVC控制器内部的私有方法是线程安全的

spring-mvc

据我了解,Spring MVC控制器默认情况下是线程安全的(例如Servlet)。但是我只想知道控制器内部的任何私有帮助器方法是线程安全的吗?

我在控制器类中有两个映射,例如:/ test和test /
success。每次用户调用此URL时,我想使用一种服务方法(两个不同的调用)来检查数据库中的用户状态和激活时间。因此,我决定创建一个私有助手方法来检查状态。谁能知道我的私有方法是线程安全的?


阅读 451

收藏
2020-06-01

共1个答案

小编典典

所有请求均由控制器的一个实例处理(单例,因为它是一个Spring托管bean)。因此,您需要确保不存储与一个请求相关的任何状态(在字段中)。

所以:

@Controller
@RequestMapping("/foo")
public class Foo {
    @Autowired
    private Something something;

    @RequestMapping("/list")
    public String foo() {
       something.someMethod();
       bar();
       return "view"
    }

    private void bar() {
        // something
    }
}

可以,但是:

@Controller
@RequestMapping("/foo")
public class Foo {

    private User theUser; // problem is ALL request share this field

    @RequestMapping("/foo/{userId}")
    public String foo(@PathVariable final Integer userId) {
       if (theUser.getId().equals(userId)) {
           // something
       } else {
           theUser = ...
       }
       return "view"
    }
}

不是。

注意:未经测试(在此处键入内容可能会伤害您的编译器)

2020-06-01