Is there a way to set up such enum values via Spring IoC at construction time?
What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below:
public enum Car { NANO ("Very Cheap", "India"), MERCEDES ("Expensive", "Germany"), FERRARI ("Very Expensive", "Italy"); public final String cost; public final String madeIn; Car(String cost, String madeIn) { this.cost= cost; this.madeIn= madeIn; } }
Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.
You can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.
There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.
A perfectly functional method of injecting enum values in CDI. You will, however, need to make sure you know which type of enum you want to inject, and if you need multiple types, then you'll need to create qualifiers for each value.
IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.
Do you mean setting up the enum
itself?
I don't think that's possible. You cannot instantiate enums because they have a static
nature. So I think that Spring IoC can't create enums
as well.
On the other hand, if you need to set initialize something with a enum
please check out the Spring IoC chapter. (search for enum) There's a simple example that you can use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With