static blocks are invoked when the class is being initialized, after it is loaded. The dependencies of your component haven't been initialized yet. That is why you get a NullPointerException (Your dependencies are null) .
Move your code to a method annotated with @PostConstruct. This will ensure that your code will run when all the dependencies of your component are initialized
譯文:static模塊會被引入,當class加載后。你的component組件的依賴還沒有初始化。這就是為什么你的代碼塊會報空指針異常。(你的依賴都是null)
1,@PostConstruct 注解的方法在加載類的構造函數之后執行,也就是在加載了構造函數之后,
為此,可以使用@PostConstruct注解一個方法來完成初始化,
@PostConstruct注解的方法將會在依賴注入完成后被自動調用。
2,執行優先級高於非靜態的初始化塊,它會在類初始化(類加載的初始化階段)的時候執行一次,執行完成便銷毀,它僅能初始化類變量,即static修飾的數據成員。
初始化失敗:
static {
strategyMap.put(SYSTEM, applicationContext.getBean(XXX.class));
System.out.println("初始化完成" + strategyMap.size());
}
初始化成功:
@PostConstruct
void init() {
strategyMap.put(SYSTEM, applicationContext.getBean(XXX.class));
System.out.println("初始化完成" + strategyMap.size());
);
}