Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Spring IoC to set up enum values

Tags:

java

enums

spring

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.

like image 892
Olivier Avatar asked Apr 02 '09 16:04

Olivier


People also ask

Can you assign values to enums?

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.

How do I assign an enum to a string?

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.

Can you inject an enum?

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.

Can you convert string to enum?

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.


1 Answers

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.

like image 57
bruno conde Avatar answered Sep 25 '22 03:09

bruno conde