考虑以下枚举:
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;
}
}
以下代码在单元测试环境中工作。
在Spring上下文中使用时,getCardType始终返回null。
EnumBrand enumBrand = EnumBrand.fromName("VISA");
EnumCardType enumCardType = enumBrand.getCardType();
我猜测涉及静态初始化,但我想了解为什么这对Spring不起作用