2011-08-06 29 views
0

我想根據請求參數在不同的服務對象上調用方法。我有這個目前..Spring的自動佈線服務

@Controller 
public class HomeController { 

@Autowired 
AService aService; 

@Autowired 
BService bService; 

@RequestMapping(value="home", method = RequestMethod.GET) 
public String checkList(ModelMap modelMap, HttpServletRequest request){ 
    String checkList = request.getParameter("listType"); 
      if("listType" == "a") 
      modelMap.addAttribute("list", aService.getList()); 
      if("listType" == "b") 
      modelMap.addAttribute("list", bService.getList()); 

    return "checklist"; 
} 
} 

所以我在想,如果我可以使用反射樣的方法來調用正確的服務對象,而不是如果條件..我剛纔的意思是,我們有AService和BService實現共同的界面和實例化正確的對象,像這樣反映..

 String classname = (String) request.getAttribute("classname"); 
     Class classref = Class.forName(classname); 
     Constructor c = classref.getConstructor(null); 
     ServiceInterface sI = c.newInstance(null); 

但隨着春天,我已經與自動裝配實例化對象,使有沒有什麼辦法來實現這一目標?

回答

0

反思幾乎總是一個壞主意,也是一個糟糕的面向對象設計的標誌。

爲避免你的if語句(其中,恕我直言,除非它被重複過很多次,可維護,可讀性強,易於理解,測試和調試),你可以存儲你的兩個服務實例在地圖:

Map<String, ServiceInterface> services = new HashMap<String, ServiceInterface>(); 
services.put("a", aService); 
services.put("b", bService); 

//... 
String checkList = request.getParameter("listType"); 
ServiceInterface service = this.services.get(checkList); 
modelMap.addAttribute("list", service.getList()); 

如果這是在幾類重複,把這個地圖到名爲ServiceInterfaceFactory一個單獨的Spring bean,幷包含一個方法ServiceInterface create(String checkList)

+0

謝謝JB ...我現在要用map ... – RKodakandla

0

如果可能的話,使雙方的服務實現相同的接口,並編寫實例化一個工廠方法你需要的那個。

相關問題