Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define Spring bean with a Map-typed constructor argument

Tags:

spring

grails

In my Grails app, I'm trying to define a Spring bean in resources.groovy that requires a Map-typed constructor arg. I tried this:

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

But I get the error message:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myBean': Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

The implementation class has a single constructor which is defined thus

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

My guess is that the problem is caused by the fact that I've defined a constructor that takes a single Map arg which has the same signature as the default constructor Groovy adds to every class.

If so, a solution would appear to be to add a factory method such as

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

But I'm not sure how I can call this to define a bean (in resources.groovy) that is constructed from a factory method that requires a parameter.

like image 892
Dónal Avatar asked Dec 13 '25 12:12

Dónal


1 Answers

As far as I can tell the syntax you're using ought to work. Does the alternative syntax:

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

work any better in your case? Failing that, declaring the map as a bean in its own right should definitely do it:

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

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

myBean(MyBeanImpl, classMap /* this is a RuntimeBeanReference */)
like image 126
Ian Roberts Avatar answered Dec 16 '25 05:12

Ian Roberts