0

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?

CodeChimp
  • 8,016
  • 5
  • 41
  • 79
  • 1
    I would suggest you store, at most, only the message code in your enum. Your current design couples your enum very closely to a servlet environment - what if you wanted to use this enum elsewhere in the future? – Duncan Jones May 21 '13 at 19:36
  • I would like that approach, but the Spring form:options does not allow me to set the label using a resource bundle. The only way I can see to do it is to resolve the message key in the Enum. – CodeChimp May 21 '13 at 19:41

2 Answers2

2

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

Community
  • 1
  • 1
Tom McIntyre
  • 3,620
  • 2
  • 23
  • 32
0

You can also see my answer in here. It doesn't not inject it but use it as a static method.

Community
  • 1
  • 1
Guito
  • 1,181
  • 1
  • 9
  • 19