I want to call method on different service objects based on a request parameter. I have this currently..
@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..
String classname = (String) request.getAttribute("classname");
Class classref = Class.forName(classname);
Constructor c = classref.getConstructor(null);
ServiceInterface sI = c.newInstance(null);
But with Spring, I already have the objects instantiated with AutoWiring so is there any way to achieve this?
Reflection is almost always a bad idea, and a sign of poor OO design.
To avoid your if clause (which, IMHO, and unless it is repeated too many times, is maintainable, readable, easy to understand, test and debug), you could store your two services instances in a map:
If this is repeated in several classes, put this map into a separate Spring bean called
ServiceInterfaceFactory, and containing a methodServiceInterface create(String checkList)