[英]Spring Bean is not initializing on Application startup
在我的應用程序中,我想在訪問應用程序URL之前初始化bean,並存儲下拉菜單的常用值。 這是bean的聲明
<beans:bean id="listService" class="com.system.beans.DropDownList"
init-method="populateMasterList" scope="application"/>
豆角,扁豆:
public class DropDownList implements InitializingBean
{
private static final Logger logger = LoggerFactory.getLogger(DropDownList.class);
public static Map<String, Map<Integer, String>> listMap = new HashMap<String, Map<Integer, String>>();
@Autowired
private static SystemService systemService;
@Autowired(required = true)
@Qualifier(value = "systemService")
public void setSystemService(SystemService systemService)
{
this.systemService = systemService;
}
@PostConstruct
public static Map<String, Map<Integer, String>> populateMasterList()
{
logger.debug("Calling Institute Info Masters");
List<InstituteInfoMaster> masterList = systemService.listInstituteInfoMasters();
Map<Integer, String> masterMap = new HashMap<Integer, String>();
masterMap.put(0, "---Select---");
masterList.forEach((master) ->
{
masterMap.put(master.getListId(), master.getValue());
});
logger.debug("Created Map for List Masters");
listMap.put("infoList", masterMap);
return listMap;
}
public Map<String, Map<Integer, String>> getListMap()
{
return listMap;
}
public static void setListMap()
{
listMap = populateMasterList();
}
@Override
public void afterPropertiesSet() throws Exception
{
populateMasterList();
}
}
我觀察到它不會在應用程序啟動時初始化。 當我嘗試通過調用DropDownList.setListMap();
更新母版時DropDownList.setListMap();
它給出了NullPointerException
。 但是,如果我在jsp頁面中調用地圖,將其稱為${listService.listMap['infoList']}
,則在我嘗試保存母版后,它將在jsp上顯示下拉列表,如果它成功執行。
這意味着當我調用那時候我顯示下拉菜單的jsp頁面時,它只會在應用程序啟動時初始化bean。
實際的問題是您不是靜態訪問Spring bean而是類。 當您使用bean(即listService
實例)時,Spring會在首次訪問時為您listService
它。
您正在調用靜態方法,但是發生這種情況時,不會填充從屬bean。 自動裝配適用於實例(即在非靜態上下文中),因此systemService
在您的應用程序中為null
。
更新:我剛剛意識到這一行:
@Autowired
private static SystemService systemService;
這根本是錯誤的。 您無法自動裝配靜態字段,在Spring(或任何類似框架)中這絕對沒有意義。 Spring Bean是實例,並且框架將自動裝配的字段設置為對其他Spring Bean的引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.