Search code examples
javarestspring-mvcfactory-pattern

Instantiating bean using factory pattern in Spring MVC 3


I got Object coming in a REST web service controller's web method which is locally initialized.

@RequestMapping(method = RequestMethod.POST,value = "/test",headers="Accept=*/*")
    public @ResponseBody ModelAndView computeDetails(@RequestBody RequestObj reqObj, ModelMap model) {

        System.out.println(reqObj.getcode());

        return new ModelAndView("responsedetails", "object", reqObj);
    }

This RequestObj object holds the key code to instantiate dependency using factory.

Different codes classes have been defined which implement BaseCode Interface.

How can I use factory method to instantiate particular code class based on code value coming in as BaseCode type in my service bean?

Any idea? Thanks in advance.


Solution

  • I did it this way -

    Make your factory as ServletContextAware in a way to get the currentContext. And define getInstance method as

    WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    
    ctx.getBean(classNameToBeInstantiated);
    

    Define your bean's inheritance in spring context so that Spring injects its dependencies.