2013-12-16 52 views
1

我得到Object在REST web service controller's Web方法中进行本地初始化。在Spring MVC中使用工厂模式实例化bean 3

@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); 
    } 

此RequestObj对象拥有使用工厂实例化依赖项的密钥code

已定义实现BaseCode接口的不同代码类。

如何使用工厂方法来实例化特定的代码类,这些代码类是基于我的服务bean中BaseCode类型的代码值进行实例化的?

有什么想法?提前致谢。

回答

0

我就是这么做的 -

让你的工厂为ServletContextAware的方式获取currentContext。并定义getInstance方法为

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); 

ctx.getBean(classNameToBeInstantiated); 

定义您的bean在Spring上下文中的继承,以便Spring注入其依赖项。

0

我不确定我是否理解你的问题,但一般情况下,春天的依赖在这里没有任何关系。只需编写自定义Factory类并根据reqObj.getcode()返回BaseCode实现。

+0

HI czajek,问题是这个reqObj没有通过spring context来实例化它的本地方法。如何将此本地对象中的此密钥传递给自定义工厂类。 – AmitN

1

我通常在这种情况下,做的是:

  1. 注入出厂到使用Spring的豆
  2. 创建的工厂方法getBaseCode(String code)控制器(请注意:String这里代表代码类型,所以使用实际的代码类型如果没有String
  3. 使getBaseCode而构建真正落实
  4. 苏返回BaseCode接口pposing你有BaseCodeexecute方法,使用getBaseCode方法到控制器,以获得真正的合作者,然后调用execute方法来执行实际的行动


忽略的第一点(我认为你可以很容易看任何Spring教程)工厂将会像

public class BaseCodeFactory { 
    public BaseCode getBaseCode(String code) { 
    if(code.equals("something")) return new ThisBaseCodeImpl(); 
    else //and so on 
    } 
} 

computeDetails变成类似于:

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

作为一个方面说明,我不会选择像我在这里选择的名称,我建议你在你的域中寻找更有意义的东西(例如BaseCode没有意义),请将此片段作为指令。

根据OP评论。如果你有ThisBaseCodeImpl这使得使用其他的Spring bean可以

  1. @Configurable所以对它进行注释,当你使用它的new ThisBaseCodeImpl(/*args if you like*/)豆是由Spring实例化。我个人不喜欢这个解决方案,因为在我看来,它用隐藏的Spring bean来污染代码。另一方面是非常灵活的,因为它允许您管理运行时构造函数参数和Spring beans
  2. ThisBaseCodeImpl添加到Spring上下文并更改工厂,以便为其注入ThisBaseCodeImpl的协作者。

1点例如:

@Configurable 
public class ThisBaseCodeImpl { 
    @Resource 
    private Bean bean; 
} 

第二点例如:

public class BaseCodeFactory { 
    @Resource 
    ThisBaseCodeImpl thisBaseCodeImpl; 

    public BaseCode getBaseCode(String code) { 
    if(code.equals("something")) return thisBaseCodeImpl; 
    else //and so on 
    } 
} 
+0

是这样的,但在这种情况下,对于ThisBaseCodeImpl的依赖注入将不会被Spring处理。这是缺点。我确实设法使用WebApplicationContext getbean方法实例化bean。所以依赖关系由spring来管理。 – AmitN

+0

@AmitN,对不起,我不清楚你希望你的'BaseCode'实现有由Spring管理的依赖项。我会更新我的答案,为您的案例提供其他两种可能的解决方案。 – ThanksForAllTheFish

相关问题