2009-10-19 49 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" } 
      } 
    } 
}