Reputation: 1688
I have a SpringBoot 2.0.5.RELEASE project with some Rest Controllers.
in my of the controller I have this method:
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);
}
Since MenuAlertEnum are app. constants and will have always the same values I want to put it as a static variable in the controller to make it faster, but By default, a spring bean is a singleton I think is not a good practice ?
Upvotes: 0
Views: 4461
Reputation: 186
Java Enum
was created to avoid using public static final String CONSTATNT_VALUE = "FOO"
. You can call enums anywhere from a static context, so there is no need to create any static blocks.
@GetMapping(path = "/menu", consumes = "application/json", produces = "application/json")
public List<MenuAlertEnum> menus() {
return Arrays.asList(MenuAlertEnum.values());
}
Arrays.asList()
and static MenuAlertEnum.values()
- easy to read and only one line of code. Hope you'll find it useful :)Upvotes: 1
Reputation: 5182
There should be no issues accessing static data from a singleton bean, beyond any normal concurrency concerns.
If you prefer not to use static variables, you could use @PostConstruct
in your controller to initialize a local variable instead:
private List<String> alerts;
....
@PostConstruct
public void setup() {
alerts = Arrays.stream(MenuAlertEnum.values())
.map(MenuAlertEnum::getAlertName)
.collect(Collectors.toList());
}
Upvotes: 3
Reputation: 501
You can use Static Block of Java to initialize the value. It just run once.
static List<String> alertNames;
static {
alertNames = Arrays.stream(MenuAlertEnum.values())
.map(MenuAlertEnum::getAlertName)
.collect(Collectors.toList());
}
And then use alertNames in your controller directly.
Upvotes: 2