Search code examples
javaspringspring-ioc

Injecting MessageSource into an Enum


I am trying to use an ENUM for a form:select as such:

<form:select path="myEnum">
  <form:options itemLabel="resourceBundleLabel" />
</form:select>

With an Enum that looks something like:

public enum MyEnum {
  ONE("rb.one"), TWO("rb.two");

  private MessageSource messageSource;

  private String rbKey;

  public String getResourceBundleLabel() {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    Locale locale = request.getLocale();
    return messageSource.getMessage(this.rbKey, null, locale);
  }

  public MyEnum(String rbKey) {
    this.rbKey = rbKey;
  }
}

The problem is that I can't seem to figure out how to get the MessageSource injected. I tried adding @Component and @Autowired (got an error because there was no default constructor. I then tried switching @Component to @Configurable. Then I tried removing both annotation, and implementing MessageSourceAware. In all cases, the messageSource is null when I get inside the getResourceBundleLable().

Ultimately, what I am trying to accomplish is to build out the select options using an Enum, but make it such that is uses the proper Resource Bundle and local. Am I just wasting my time on something that is not feasible?


Solution

  • See my answer here for how to inject dependencies into enums with minimal plumbing.