Nuñito Calzada
Nuñito Calzada

Reputation: 1688

Use static variables in a RestController in a SpringBoot project

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

Answers (3)

Rostyslav Barmakov
Rostyslav Barmakov

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());
}
  • only static Arrays.asList() and static MenuAlertEnum.values() - easy to read and only one line of code. Hope you'll find it useful :)

Upvotes: 1

Mike
Mike

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

Bendy Zhang
Bendy Zhang

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

Related Questions