tags:

views:

477

answers:

2

Hi,

I'm trying to inject a Map into a Grails controller. I want to inject the same map into many controllers so would like to define it in resources.groovy.

I've looked on the web but can't find an example of creating a simple map.

In Spring MVC I've used something like this:

<util:map id="diplomaPermissions">
   <entry>
      <key>1</key>
      <value>Diploma_AQA_Building_And_Construction</value>
   </entry>
   <entry>
      <key>1</key>
      <value>Diploma_Edexcel_Building_And_Construction</value>
   </entry>
</util:map>

With this in my xml header:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/util 
        http://www.springframework.org/schema/util/spring-util-2.5.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-2.5.xsd"&gt;

But this doesn't seem to work in grails if I use the spring xml files.

Any tips appreciated.

+2  A: 

I think it might be related to the version of spring you are expecting; when using the old style for creating map, everything works fine.

try this in your resources.xml in the spring configuration directory

<bean id="testMap" 
     class="org.springframework.beans.factory.config.MapFactoryBean">
  <property name="sourceMap">
      <map>
        <entry key="key1" value="value1"/>
        <entry key="key2" value="value2"/>
      </map>
  </property>
</bean>

and this on your controller

class DisplayMapController {
    def  testMap

    def index = {  
     render (contentType: "text/plain") {
                    div(id:"myDiv") { p "$testMap" }
            }
    }
}
Aaron Saunders
+3  A: 

after further investigation, you can create the map in "resources.groovy"

    beans = {
        diplomaPermissions(org.springframework.beans.factory.config.MapFactoryBean) {
     sourceMap = [
                  1:"Diploma_AQA_Building_And_Construction", 
                  2:"Diploma_Edexcel_Building_And_Construction" 
                ] 
        }
    }
Aaron Saunders
Thanks for the answers. I put it in Config.groovy in the end but this helps for other maps we may well need to define. Thanks again.
Matt