我有一个带有一些Rest Controller的SpringBoot 2.0.5.RELEASE项目。
在我的控制器中,我有以下方法:
GetMapping(path = "/menu", consumes = "application/json", produces = "application/json")
public ResponseEntity<List<String>> menus() {
List<String> result = Arrays.stream(MenuAlertEnum.values())
.map(MenuAlertEnum::getAlertName)
.collect(Collectors.toList());
return ResponseEntity.ok(result);
}
由于MenuAlertEnum是应用程序。常量,并且将始终具有相同的值,我想将其作为静态变量放入控制器中以使其更快,但是默认情况下,spring bean是单例,我认为这不是一个好习惯吗?
最佳答案
您可以使用Java的静态块来初始化该值。它只运行一次。
static List<String> alertNames;
static {
alertNames = Arrays.stream(MenuAlertEnum.values())
.map(MenuAlertEnum::getAlertName)
.collect(Collectors.toList());
}
然后直接在您的控制器中使用alertNames。