views:

1471

answers:

2

I have a class which constructor takes a Jakarta enums. I'm trying to find how I can easily inject it via an Spring XML aplicationContext.

For example :

The enum :

public class MyEnum extends org.apache.commons.lang.enums.Enum {
    public static final MyEnum MY_FIRST_VALUE = new MyEnum("MyFirstValue");
    public static final MyEnum MY_SECOND_VALUE = new MyEnum("MySecondValue");

    public static MyEnum getEnum(String name) {
        return (MyEnum) getEnum(MyEnum.class, name);
    }
    [...other standard enum methods]
}

The class in which to inject :

public class MyService {
    private final MyEnum status;
    public MyService(MyEnum status) {
        this.status = status;
    }
}

The application context :

<bean id="myService" class="MyService">
    <constructor-arg index="0" value="MyFirstValue" />
</bean>

Of course, with this I have a no matching editors or conversion strategy found error. Is there an easy integration between Spring and the Jakarta enums ? Or should I write my own PropertyEditor ?

+1  A: 

I found a solution, but it is very verbose (far too much to my taste) :

<bean id="myService" class="MyService">
    <constructor-arg index="0">
        <bean class="MyEnum" factory-method="getEnum">
            <constructor-arg value="MyFirstValue" />
        </bean>
    </constructor-arg>
</bean>
Guillaume
+1  A: 

Check out the <util:constant> tag in Spring. It will require you to add the schema to your xml definition. So you would wind up with the following:

<bean id="myService" class="MyService">
  <constructor-arg index="0">
    <util:constant static-field="MyEnum.MY_FIRST_VALUE"/>
  </constructor-arg>
</bean>

The definition and usage of the tag (including the XSD def) is found here.

Spencer K