1. 程式人生 > >記錄手寫一次ssm框架遇到的一些坑之注入失敗

記錄手寫一次ssm框架遇到的一些坑之注入失敗

由於沒有實現單例或者說再contrllerMap和iocMap中實現同一個類兩個物件,導致僅僅注入其中一個物件的坑

簡介

  • 最近一直在嘗試實現一個自己的ssm框架,前斷時間已經分別實現了mvc 和 mybatis,其中在實現mvc的時候沒有實現autowired註解,在整合ssm框架的時候開始實現,但是卻碰上了問題(最近有時間的話,我會分別為之前實現的mvc和mybatis分別寫一個框架的,這次也不全部分享原始碼,等有空全部實現後再分享上來)

檔案目錄結構

在這裡插入圖片描述

出現的問題

  • 在下圖中的controller中,我進行注入一個service,但是在請求連結的時候,呼叫的方法中呼叫了userServiceImpl,但是提示userServiceImpl為空
  • 在這裡插入圖片描述
  • 我到MyDispatcherServlet類中檢視我實現ioc的程式碼
 private void doIoc(){
    	if(ioc.isEmpty()) return ;
    	for(Entry<String, Object> entry : ioc.entrySet()){
    		Field[] fields = entry.getValue().getClass().getDeclaredFields();
    		for(Field field : fields){
    			 field.setAccessible(true);
    			if(field.isAnnotationPresent(MyAutowired.class)){
    				String autowiredValueName = field.getAnnotation(MyAutowired.class).value();
    				if(autowiredValueName == null || autowiredValueName.equals("")){
    					autowiredValueName = toLowerFirstWord(field.getType().getSimpleName());
    				}
    				field.setAccessible(true);
    				try {
    					field.set(entry.getValue(), ioc.get(autowiredValueName));
    					
					} catch (IllegalArgumentException e) {
						// TODO: handle exception
						e.printStackTrace();
					}catch (IllegalAccessException  e) {
						// TODO: handle exception
						e.printStackTrace();
					}
    			}
    		}
    		
    	}
    	
    }
 

  • 經過一系列各種判斷,我確認我應該已經將userServiceImpl物件賦予了ioc容器中相應物件值了
    經過一系列檢查發現,當時候實現mvc的時候服務controllerMap的物件和iocMap中的物件不是同一個物件,都是newInstance 出來的,最後我將賦值的物件改為同一個物件,最後成功了。