2013-04-10 76 views
1

如何將我在Spring DSL中聲明的列表綁定到我的服務的參數?在Spring中綁定Spring Beans到服務?

我有以下豆聲明

beans = { 
    defaultSkillList = [ 
     { Skill s -> 
      name="Shooting"  
      description = "Shooting things..."}, 
    { Skill s -> 
      name="Athletics" 
      description = "Running, jumping, dodging ..."} 
    ] 
} 

而且我有以下服務聲明:

class GameService { 

    def defaultSkillList 

    def createGame(Game gameInstance) { 
     //... 
    } 
} 

試圖訪問defaultSkillList當我目前得到NullReferenceException

我該如何訪問這個bean?

回答

3

你不能聲明一樣,在豆類DSL的列表,你需要像

beans = { 
    defaultSkillList(ArrayList, [....]) 
} 

但DSL不會讓你定義匿名內部Bean的列表(當然,它將接受語法defaultSkillList(ArrayList, [{Skill s -> ...}, ... ],但它會給你一個閉包列表,而不是把閉包當作bean定義)。您需要用名稱聲明各個bean,然後使用它們,例如ref

beans = { 
    'skill-1'(Skill) { 
    name="Shooting"  
    description = "Shooting things..." 
    } 
    'skill-2'(Skill) { 
    name="Athletics" 
    description = "Running, jumping, dodging ..." 
    } 

    defaultSkillList(ArrayList, [ref('skill-1'), ref('skill-2')]) 
} 

或乾脆放棄在DSL和grails-app/conf/spring/resources.xml使用XML來代替:

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/util 
     http://www.springframework.org/schema/util/spring-util.xsd"> 

    <util:list id="defaultSkillList"> 
    <bean class="com.example.Skill" p:name="Shooting" p:description="..." /> 
    <bean class="com.example.Skill" p:name="Athletics" p:description="..." /> 
    </util:list> 
</beans> 
+0

酷,沒什麼大不了的,我使用的春天格式。該服務是正確定義的權利? – 2013-04-10 17:55:19