private method inside spring mvc controller is thr

2019-07-19 05:56发布

问题:

As i understand spring mvc controllers are thread safe by default (like servlets). But I just want to know any private helper methods inside the controllers are thread safe ?

I have two mapping in the controller class eg: /test and test/success. Every time user invokes this url I want to check the user status and activation time in the database using a service method ( two different calls ). So I have decided to create a one private helper method to check the status. So could anyone know that my private method is thread safe ?

回答1:

All request are handled by one instance of your controller (singleton because it's a spring managed bean). So you need to make sure to not store any state (in a field) related to one request.

So:

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

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

    private void bar() {
        // something
    }
}

is OK, but:

@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"
    }
}

is not.

NB: not tested (typed just here so it can even hurts your compiler)