I want to call method on different service objects based on a request parameter. I have this currently..
Code:@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"; } }
So I was wondering if I can use reflection kind of methodologies to call correct service object instead of if conditions.. I mean earlier, we had AService and BService implementing a common interface and instantiate correct object with reflection like this..
But with Spring, I already have the objects instantiated with AutoWiring so is there any way to achieve this?Code:String classname = (String) request.getAttribute("classname"); Class classref = Class.forName(classname); Constructor c = classref.getConstructor(null); ServiceInterface sI = c.newInstance(null);


Reply With Quote
