抽象类中的Grails服务

时间:2013-10-17 19:41:11

标签: spring grails groovy abstract-class

我有一个很多类扩展的抽象类。一切都在src/groovy

在我的抽象类中,我希望注入一个子类继承的服务,所以我不必每次都注入它们。

abstract class Animal {

    def noiseService

    abstract Sound getSound()

}

class Dog extends Animal {

    Sound getSound() {
        noiseService.bark()
    }

}

在我的resources.groovy:

animal(com.thepound.Animal) { bean ->
    noiseService = ref("noiseService")
}

这产生了一个错误,说它无法实例化该类,因为它是抽象的,所以我将它添加到定义中:

    bean.abstract = true

现在我不再收到错误,但是我的子类中的服务始终为null。我怎样才能让它发挥作用?

2 个答案:

答案 0 :(得分:1)

这是我最终做的事情。

我按照Burt Beckwith的帖子http://burtbeckwith.com/blog/?p=1017来创建ApplicationContextHolder类。

然后

abstract class Animal {

    def noiseService = ApplicationContextHolder.getBean("noiseService")

    abstract Sound getSound()

}

现在可行了

class Dog extends Animal {

    Sound getSound() {
        noiseService.bark()
    }

}

对于DogAnimal

,我无需在resources.groovy中添加任何内容

答案 1 :(得分:0)

如果你想实例化狗,就这样做:

noiseService(com.whatever.DogNoiseService) { bean ->
}

animal(com.thepound.Dog) { bean ->
    noiseService = ref("noiseService")
}