0

I get enum value as input, each enum value corresponds to a class. How do I define spring configuration given enum value should convert to class object

public enum R {
eR1,
eR2,
eR3;
}

//simple interface
interface R {
    dosomething();
}

//R1 class
class R1 implements R {
    dosomething() {
    //implmentation for R1
    }
}

//R2 class
class R2 implements R {
    dosomething() {
        //implementation for R2
    }
}

I have API say,

getR(R er1) {
   //How do I define spring configuration to get class object given enum value??
}

I want to avoid if conditions in API, something like this
getR(R er) {
    if(er.equals(R.eR1)) {
        //do this
    } else if(er.equals(R.eR2)) {
       //do this
    }
}
I want to spring to inject right class based on input parameter so that I can avoid if statement.

say for three enum fields I want to avoid having three id's in spring.

Can I define somethign like this
<bean id="r" class="com.myProject.R1">
    <property name="er1" value="eR1"/>
</bean>
<bean id="r" class="com.myProject.R2">
    <property name="er2" value="eR2"/>
</bean>
//similary for R3 as well
Kira
  • 91
  • 2
  • 7

1 Answers1

1

In your spring configuration just use the enum value

sample if you want to inject eR2 inside R2 ,

 <bean id="r2" class="com.myProject.R2">
     <property name="er2" value="eR2"/>
 </bean>

see a sample here . You need not use the fully qualified name . See a discussion at How assign bean's property an Enum value in Spring config file? .

Community
  • 1
  • 1
Aravind A
  • 9,507
  • 4
  • 36
  • 45