How to assign bean's property an Enum value in Spring config file?

前端 未结 9 887
遥遥无期
遥遥无期 2020-11-28 06:16

I have a standalone enum type defined, something like this:

package my.pkg.types;

public enum MyEnumType {
    TYPE1,
    TYPE2
}

Now, I w

相关标签:
9条回答
  • 2020-11-28 06:22

    You can just do "TYPE1".

    0 讨论(0)
  • 2020-11-28 06:24

    I know this is a really old question, but in case someone is looking for the newer way to do this, use the spring util namespace:

    <util:constant static-field="my.pkg.types.MyEnumType.TYPE1" />
    

    As described in the spring documentation.

    0 讨论(0)
  • 2020-11-28 06:28

    Have you tried just "TYPE1"? I suppose Spring uses reflection to determine the type of "type" anyway, so the fully qualified name is redundant. Spring generally doesn't subscribe to redundancy!

    0 讨论(0)
  • 2020-11-28 06:29

    Use the value child element instead of the value attribute and specify the Enum class name:

    <property name="residence">
        <value type="SocialSecurity$Residence">ALIEN</value>
    </property>
    

    The advantage of this approach over just writing value="ALIEN" is that it also works if Spring can't infer the actual type of the enum from the property (e.g. the property's declared type is an interface).Adapted from araqnid's comment.

    0 讨论(0)
  • 2020-11-28 06:36

    Using SPEL and P-NAMESPACE:

    <beans...
    xmlns:p="http://www.springframework.org/schema/p" ...>
    ..
    <bean name="someName" class="my.pkg.classes"
        p:type="#{T(my.pkg.types.MyEnumType).TYPE1}"/>
    
    0 讨论(0)
  • 2020-11-28 06:36

    This is what did it for me MessageDeliveryMode is the enum the bean will have the value PERSISTENT:

    <bean class="org.springframework.amqp.core.MessageDeliveryMode" factory-method="valueOf">
        <constructor-arg value="PERSISTENT" />
    </bean>
    
    0 讨论(0)
提交回复
热议问题