2009-10-19 52 views
3

我试图向Grails控制器注入一个Map。我想将相同的地图注入许多控制器,所以想在resources.groovy中定义它。注入一个简单的地图到Grails控制器中

我在网上看过,但找不到创建简单地图的例子。

在Spring MVC我用这样的:

<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> 

有了这个在我的XML头:

<?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"> 

但是,这似乎并没有在Grails的工作,如果我用的是春天的XML文件。

任何提示赞赏。

回答

9

在进一步调查后,你可以创建“resources.groovy”地图

beans = { 
     diplomaPermissions(org.springframework.beans.factory.config.MapFactoryBean) { 
     sourceMap = [ 
        1:"Diploma_AQA_Building_And_Construction", 
        2:"Diploma_Edexcel_Building_And_Construction" 
       ] 
     } 
    } 
+0

感谢您的回答。我最终将它放在Config.groovy中,但这对我们可能需要定义的其他地图有帮助。再次感谢。 – Matt 2009-10-21 10:49:10

2

我想它可能与你期待的春天的版本有关;当使用旧式创建地图时,一切正常。

春天配置目录

<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> 

试试这个在您的resources.xml中,该控制器

class DisplayMapController { 
    def testMap 

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