0

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.

DPM
  • 1,960
  • 3
  • 26
  • 49

1 Answers1

1

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>
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • perfect, thanks, I found a very similar solution using factory-bean and factory-method and I was about to post it, so I know this works – DPM Feb 09 '18 at 16:28