Announcement Announcement Module
No announcement yet.
Inject a dependency into an enum Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Inject a dependency into an enum

    Hello all,

    I'm trying to inject a dependency into an enum that its constants implement a method. I've tried several tactics, traveled the web, but yet haven't found an answer. I'll just paste here sample code and I'd be happy for any help.

    Thank you,

    public class SomeBean {}
    public enum InjectThisEnum {
        POSSIBLE( true ) {
            public void doNothing(){}
        }, NOT_POSSIBLE( false ) {
            public void doNothing(){}
        }, POSSIBLE_BUT_NOT_NEAT( true ) {
            public void doNothing(){}
        abstract public void doNothing();
        private SomeBean someBean;
        InjectThisEnum( boolean b ) {}
        public SomeBean getSomeBean() {
            return someBean;
        public void setSomeBean(SomeBean someBean) {
            someBean = someBean;

  • #2
    That is not going to happen. You cannot instantiate enums, they are already there and are more or less static. The only change you have is a dependency lookup, create a holder (ugly singleton) for you applicationcontext and use that to retrieve the context and get the bean(s) you need.


    • #3
      Hi Marten,

      Thanks for the answer. Unfortunately I already have an ApplicationContext which is not a singleton and is not going to be a singleton sometime soon...

      I thought maybe to init the class member using an aspect... Which is not what aspects were designated for but should do the work - not elegantly.

      So, now I think about wrapping it with a simple class that its init method will call the enum's member's setter... (setSomeBean(SomeBean) in the sample code above).

      Is there a reason that Spring don't let dependency injection into enums? They can be aspected automatically by Spring so that field members like SomeBean above will be set before any other method is invoked (except for those invoked in constructors and maybe static blocks).
      Or at least let enums have a static init method, like normal classes have...

      Thank you again for the time.


      • #4
        Well actually I cincerly hope for your sake that you only have a single instance of your app context! If you don't you are probably going to run out of resources. Although enums are more or less like normal classes they are different. Although you could try with an aspect, probably a ApplicationListener which acts upon the ContextRefreshedEvent would also do the trick.


        • #5
          Well actually I cincerly hope for your sake that you only have a single instance of your app context!
          I sure hope so too! :-)

          Anyway, wrapping it with one of my relevant already existing beans and letting initializing the property, did well.