我想知道是否可以将临时数据存储在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);
}
}
}
我知道Controllers
是Beans
,并且我知道Beans
是Singleton
,所以:
如果两个用户同时调用test
方法会怎样?
他们每个人都读/写相同的testMap
对象吗?
当testMap
对象失去作用域并重新实例化吗?
谢谢
答案 0 :(得分:1)
是的,两个请求将操作相同的testMap
对象。如果要为每个请求创建一个新的Map
,则可以在一个配置类中为其创建一个bean:
@Bean
@RequestScope // or @Scope("request")
public Map<Integer, Test> testMap() {
return new HashMap<>();
}
并自动将其连接到您的控制器中:
@Autowired
private Map<Integer, Test> testMap;