SpringBoot 列舉類報錯ExceptionInInitializerError的分析與解決
今天下午使用這個列舉類一直報錯ExceptionInInitializerError,一直弄了快2個小時才排查出原因,終於發現和解決了!
檢查常量與列舉類是否存在相互依賴!!
報錯的程式碼如下:
public class TestEnumClass { /** * 監控項 */ public enum ITEM { ITEMA(0.1, "ITEMA",AlarmClass.Monitor.alarmKeyA), ITEMB(0.9, "ITEMB",AlarmClass.Monitor.alarmKeyB); private Double value; private String name; private String alarmKey; ITEM(Double value, String name, String alarmKey) { this.value = value; this.name = name; this.alarmKey = alarmKey; } public Double getValue() { return value; } public String getName() { return name; } public String getAlarmKey() { return alarmKey; } } }
public class AlarmClass {
public static class Monitor{
public static final String alarmKeyA = "alarm_" + TestEnumClass.ITEM.ITEMA.getName();
public static final String alarmKeyB = "alarm_" + TestEnumClass.ITEM.ITEMB.getName();
}
}
public class TestPO { private String name; private Double rate; public TestPO(String name, Double cityName2) { this.name = name; this.rate = rate; } }
定時任務類中的靜態程式碼塊:
static {
System.out.println(TestEnumClass.ITEM.ITEMA.getName());
TestPO testPO = new TestPO(TestEnumClass.ITEM.ITEMA.getName(),
TestEnumClass.ITEM.ITEMA.getValue());
System.out.println(1234);
}
debug專案,一直報錯:
Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1236) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance
後來發現:AlarmClass中的Monitor與TestEnumClass的ITEM存在互相依賴問題!!!
為什麼要這麼寫呢,是想是使alarmKey的後半部分與ITEM中的name保持一致,這樣以後修改一處即可。
解決方法:
方法1:AlarmClass中把Monitor內部類去掉,直接寫alarmKeyA,alarmKeyB,這樣也是報同樣的錯,說明與內部類無關。
方法2,新建:
public class SystemConstant {
public static final String ITEMA = "ITEMA";
public static final String ITEMB = "ITEMB";
}
AlarmClass中的Monitor、TestEnumClass的ITEM,都使用SystemConstant中的ITEMA、ITEMB即可,使他們解耦,這樣既實現了目的,也不會報錯!