【问题标题】:Define Spring bean with a Map-typed constructor argument使用 Map 类型的构造函数参数定义 Spring bean
【发布时间】:2012-09-07 14:29:43
【问题描述】:

在我的 Grails 应用程序中,我试图在 resources.groovy 中定义一个 Spring bean,它需要一个 Map 类型的构造函数 arg。我试过这个:

Map<Class, String> mapArg = [(String): 'foo']
myBean(MyBeanImpl, mapArg)

但我收到错误消息:

org.springframework.beans.factory.BeanCreationException: 错误 创建名为“myBean”的bean:无法解析匹配 构造函数(提示:为简单指定索引/类型/名称参数 避免类型歧义的参数)

实现类有一个这样定义的构造函数

MyBeanImpl(Map<Class, String> map) {
  // impl omitted 
}

我的猜测是,问题是由于我定义了一个构造函数,该构造函数采用单个 Map arg,其签名与 Groovy 添加到每个类的默认构造函数具有相同的签名。

如果是这样,解决方案似乎是添加工厂方法,例如

MyBean getInstance(Map map) {
  // impl omitted  
}

但我不确定如何调用它来定义一个 bean(在 resources.groovy 中),它是从需要参数的工厂方法构造的。

【问题讨论】:

  • 应该可以的。一个小问题是您需要将映射定义为带括号的[(String):'foo'],以便将Class 对象用作映射键而不是字符串“String”,但我认为泛型类型参数在判断构造函数是否匹配。
  • @IanRoberts 在代码本身中,出于您陈述的原因,我确实在类周围加了括号。我已经更新了我的问题,很好发现。

标签: spring grails


【解决方案1】:

据我所知,您使用的语法应该可以工作。是否替代语法:

Map<Class, String> mapArg = [(String): 'foo']
myBean(MyBeanImpl) { bean ->
  bean.constructorArgs = [mapArg]
}

在您的情况下工作得更好吗?如果做不到这一点,那么绝对应该将地图声明为 bean:

import org.springframework.beans.factory.config.MapFactoryBean

classMap(MapFactoryBean) {
  sourceMap = [(String):'foo']
}

myBean(MyBeanImpl, classMap /* this is a RuntimeBeanReference */)

【讨论】:

    猜你喜欢
    • 2011-12-26
    • 2021-05-25
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    相关资源
    最近更新 更多