将临时数据存储在Spring Controller中

时间:2018-07-02 13:18:55

标签: java spring spring-mvc

我想知道是否可以将临时数据存储在Controller的class属性中。 我对并发调用感到怀疑。例如,让我们考虑以下代码:

@Controller
public class TestController {
    @Autowired
    private TestService testService;

    @Autowired
    private OtherService otherService;

    private final HashMap<Integer, Test> testMap = new HashMap<Integer, Test>();

    @RequestMapping(value = "test")
    @ResponseBody
    public List<Test> test() {
        List<Test> list = new ArrayList<Test>();
        for (final OtherTest otherTest : otherService.getAll()) {
            Integer key = otherTest.getId();
            final Test t;
            if(testMap.containsKey(key)) {
                t = testMap.get(key);
            } else {
                t = testService.getByOtherTestId(key);
            }
            list.add(t);
        }
    }
}

我知道ControllersBeans,并且我知道BeansSingleton,所以:

如果两个用户同时调用test方法会怎样? 他们每个人都读/写相同的testMap对象吗? 当testMap对象失去作用域并重新实例化吗?

谢谢

1 个答案:

答案 0 :(得分:1)

是的,两个请求将操作相同的testMap对象。如果要为每个请求创建一个新的Map,则可以在一个配置类中为其创建一个bean:

@Bean
@RequestScope // or @Scope("request")
public Map<Integer, Test> testMap() {
    return new HashMap<>();
}

并自动将其连接到您的控制器中:

@Autowired
private Map<Integer, Test> testMap;