Considering the following enum :
public enum EnumBrand {
visa("VISA", EnumCardType.visa),
mastercard("MASTERCARD", EnumCardType.mastercard),
amex("AMERICAN EXPRESS", EnumCardType.amex),
maestro("MAESTRO", EnumCardType.mastercard),
unknown("UNKNOWN", EnumCardType.visa);
private String name;
private EnumCardType cardType;
EnumBrand(String name, EnumCardType cardType) {
this.name = name;
this.cardType = cardType;
}
private static final Map<String, EnumBrand> h = new HashMap<>();
static {
for (EnumBrand enumBrand : EnumBrand.values()) {
h.put(enumBrand.getName(), enumBrand);
}
}
public static EnumBrand fromName(String name) {
try {
EnumBrand type = h.get(name);
if (type == null)
return EnumBrand.unknown;
return type;
} catch (Exception e) {
return EnumBrand.unknown;
}
}
public String getName() {
return name;
}
public EnumCardType getCardType() {
return cardType;
}
}
The following code workds in a unit test context.
When used in Spring context, getCardType always return a null.
EnumBrand enumBrand = EnumBrand.fromName("VISA");
EnumCardType enumCardType = enumBrand.getCardType();
I'm guessing that the static init is involved, but I'd like to understand why exactly this doesn't work with Spring