Search code examples
javaspringenumsspring-beanspring-ioc

How to define an xml-configuration spring bean that is the result of a call to an enum's instance?


I have an enum (this is kotlin, but it doesn't matter, could be Java too)

enum class AnEnum {
  A_VALUE {
    override fun aMethod(arg: ArgClass): AClass {
       //...
    }
  };
  abstract fun aMethod(arg: ArgClass): AClass
}

I need a bean in a spring xml bean that is the result of calling "aMethod" of an enum's value.

It seems I cannot use "factory-method" for this in the usual fashion:

<bean id="myBean" class="my.pckg.AClass" factory-method="???">

I know how to get a bean of the enum's value, if that helps to break down the problem:

   <bean id="aValueBean" class="my.pckg.AnEnum" factory-method="valueOf">
        <constructor-arg>
            <value>A_VALUE</value>
        </constructor-arg>
    </bean> 

I'm at a loss as to how to create a bean of type "AClass" that is the result of calling a method with arguments on the enum instance. I'm not very experienced with spring and I have used constructors or static methods before for bean definition.


Solution

  • You could use the util:constant XML member to declare a bean for your enum constant A_VALUE

    <util:constant id="myFactory" static-field="my.pckg.AnEnum.A_VALUE" />
    

    Then use that bean as the factory-bean for your AClass bean

    <bean id="myBean" class="my.pckg.AClass" factory-bean="myFactory" factory-method="aMethod">
        <constructor-arg>
            <bean class="my.pckg.ArgClass"></bean>
        </constructor-arg>
    </bean>