Shamik
Shamik

Reputation: 7108

How to use Spring to get the value of an Enum

<bean id="xyz" class="com.abc" >
  <property name="name">
    <bean         
            class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
        <property name="staticField" value="com.abc.staticname" />
     </bean>
   </property>
</bean>

This is the way previously I used to set the name of class com.abc. Now, the names should come from another enum. How do I access the enum value to set the name property of my class com.abc?

Upvotes: 6

Views: 6372

Answers (2)

skaffman
skaffman

Reputation: 403491

I don't see why you can't keep on using FieldRetrievingFactoryBean, that's what it's for.

It's a little bit easier to use than your example suggests, though. Also, there's the easier schema-based syntax which does the same thing, <util:constant>.

Both approaches are documented (and compared) here.

(Remember that enum values are just static fields on the enum class)

Upvotes: 7

Alex Marshall
Alex Marshall

Reputation: 10312

You can just use the enum name as the value, and Spring will automatically detect that it's a static field of the enum type and use it. So for example, if you have an enum com.mycompany.MyEnum with values SOMEVAL, ANOTHERVAL, you can use :

<property name="myEnumProperty" value="SOMEVAL" />

This will allow you to avoid FieldRetrievingFactoryBean and <util:constant> altogether.

Upvotes: 2

Related Questions