2

如何将我在 Spring DSL 中声明的列表绑定到我的服务参数?

我有以下 bean 声明

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) {
       //...
    }
}

我目前NullReferenceException在尝试访问defaultSkillList.

我应该如何访问这个 bean?

4

1 回答 1

3

您不能在 bean 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 并改用 XML grails-app/conf/spring/resources.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>
于 2013-04-10T17:18:25.417 回答