Grails服务抽象类 [英] Grails services in abstract class

查看:105
本文介绍了Grails服务抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类,许多类扩展。一切都在 src / groovy 中。



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

 抽象类动物{

def noiseService

抽象声音getSound()

}

class Dog扩展动物{

Sound getSound (){
noiseService.bark()
}

}

在我的resources.groovy中:

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

说它不能实例化类,因为它是抽象的,所以我将它添加到定义中:

  bean.abstract = true 

现在,我不再收到错误,但服务在我的子类中始终为空。我怎样才能使这个工作?

解决方案

这是我最终做的。

我跟着Burt Beckwith的帖子在这里 http:/ /burtbeckwith.com/blog/?p=1017 创建一个ApplicationContextHolder类。



然后



<
$ abstract b


$ noise $ get









$ b}

现在这个作品

  class Dog extends Animal {

Sound getSound(){
noiseService.bark()
}


我没有必要在resources.groovy中放置任何动物


I have an abstract class that many classes extend. Everything is in src/groovy.

In my abstract class I would like to have a service injected that the child classes would inherit so I don't have to inject them in every single one.

abstract class Animal {

    def noiseService

    abstract Sound getSound()

}

class Dog extends Animal {

    Sound getSound() {
        noiseService.bark()
    }

}

In my resources.groovy:

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

This produced an error saying it couldn't instantiate the class because it is abstract, so I added this to the definition:

    bean.abstract = true

Now I no longer get an error, however the services are always null in my child classes. How can I get this to work?

解决方案

Here is what I ended up doing.

I followed Burt Beckwith's post here http://burtbeckwith.com/blog/?p=1017 to create an ApplicationContextHolder class.

Then

abstract class Animal {

    def noiseService = ApplicationContextHolder.getBean("noiseService")

    abstract Sound getSound()

}

Now this works

class Dog extends Animal {

    Sound getSound() {
        noiseService.bark()
    }

}

I didn't have to put anything in resources.groovy for the Dog or Animal classes

这篇关于Grails服务抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆