小编典典

将临时数据存储在Spring Controller中

spring-mvc

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

@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对象失去作用范围并会重新实例化?

谢谢


阅读 559

收藏
2020-06-01

共1个答案

小编典典

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

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

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

@Autowired
private Map<Integer, Test> testMap;
2020-06-01